WPF: Dictionary<int, List<string>> in DataGrid

别来无恙 提交于 2019-12-28 18:53:08

问题


I have a Dictionary<int, List<string>>. Each ID(int) has a corresponding dynamic list of names(List<string>).

This is the expected output in Datagrid.

ID | Name | Name | Name
1    Ash    Tina   Kara
2    Kc     
3    Star   Lara

How do I achieve this?


回答1:


 <DataGrid x:Name="dg" ItemsSource="{Binding Dic}" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="id" Binding="{Binding Key}"/>
                <DataGridTextColumn Header="Name" Binding="{Binding Value[0]}"/>
                <DataGridTextColumn Header="Name" Binding="{Binding Value[1]}"/>
                <DataGridTextColumn Header="Name" Binding="{Binding Value[2]}"/>
            </DataGrid.Columns>
        </DataGrid>

if Name is not a fixed data, you need add column dynamicly like this:

 DataGridTextColumn column = new DataGridTextColumn();
            column.Header = "name4";
            column.Binding = new Binding("Value[3]");
            dg.Columns.Add(column);

all right ,here is my code:

 <DataGrid x:Name="dg" ItemsSource="{Binding Dic}" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="id" Binding="{Binding Key}"/>
            </DataGrid.Columns>
        </DataGrid>


private Dictionary<int, List<string>> dic;

        public Dictionary<int, List<string>> Dic
        {
            get { return dic; }
            set { dic = value; }
        }

        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = this;
            Dic = new Dictionary<int, List<string>>();
            Dic.Add(1, new List<string> { "a", "b", "c", "5" });
            Dic.Add(2, new List<string> { "d" });
            Dic.Add(3, new List<string> { "e", "f" });

            int count = 0;
            foreach (List<string> lst in Dic.Values)
            {
                if (lst.Count > count)
                {

                    for (int i = count; i < lst.Count; i++)
                    {
                        DataGridTextColumn column = new DataGridTextColumn();
                        column.Header = "name" + i;
                        column.Binding = new Binding(string.Format("Value[{0}]", i));
                        dg.Columns.Add(column);
                    }
                    count = lst.Count;
                }
            }


        }

but i'd like you finish it by yourself




回答2:


Have you tried to bind to the Values collection of the dictionary? Set the dictionary.Values collection as the ItemsSource and turn on AutoGenerateColumns=True



来源:https://stackoverflow.com/questions/24361013/wpf-dictionaryint-liststring-in-datagrid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!