WPF:DataGrid 中的 Dictionary<int, List<string>>
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24361013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF: Dictionary<int, List<string>> in DataGrid
提问by for-each
I have a Dictionary<int, List<string>>. Each ID(int) has a corresponding dynamic list of names(List<string>).
我有一个Dictionary<int, List<string>>. 每个 ID(int) 都有一个对应的动态名称列表 ( List<string>)。
This is the expected output in Datagrid.
这是 Datagrid 中的预期输出。
ID | Name | Name | Name
1 Ash Tina Kara
2 Kc
3 Star Lara
How do I achieve this?
我如何实现这一目标?
回答by Rang
<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:
如果 Name 不是固定数据,则需要像这样动态添加列:
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
但我希望你自己完成
回答by BionicCode
Have you tried to bind to the Valuescollection of the dictionary? Set the dictionary.Valuescollection as the ItemsSourceand turn on AutoGenerateColumns=True
您是否尝试过绑定到Values字典的集合?将dictionary.Values集合设置为ItemsSource并打开AutoGenerateColumns=True

