我有一个Dictionary<int, List<string>>。每个ID(int)都有一个对应的动态名称列表(List<string>)。

这是Datagrid中的预期输出。

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


我该如何实现?

最佳答案

 <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>

如果Name不是固定数据,则需要像这样动态添加列:
 DataGridTextColumn column = new DataGridTextColumn();
            column.Header = "name4";
            column.Binding = new Binding("Value[3]");
            dg.Columns.Add(column);

好的,这是我的代码:
 <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;
                }
            }


        }

但我希望你自己完成

关于c# - WPF:DataGrid中的Dictionary <int,List <string >>,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24361013/

10-17 02:18