原文网址: https://www.cnblogs.com/zany-hui/articles/7623874.html
数据源格式:Dictionary<int, List<string>>
1.通过xaml设置
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
<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>
![复制代码](https://common.cnblogs.com/images/copycode.gif)
1 <DataGrid x:Name="dg" ItemsSource="{Binding Dic}" AutoGenerateColumns="False"> 2 <DataGrid.Columns> 3 <DataGridTextColumn Header="id" Binding="{Binding Key}"/> 4 <DataGridTextColumn Header="Name" Binding="{Binding Value[0]}"/> 5 <DataGridTextColumn Header="Name" Binding="{Binding Value[1]}"/> 6 <DataGridTextColumn Header="Name" Binding="{Binding Value[2]}"/> 7 </DataGrid.Columns> 8 </DataGrid>
![复制代码](https://common.cnblogs.com/images/copycode.gif)
2.通过代码设置
DataGridTextColumn column = new DataGridTextColumn();
column.Header = "name4";
column.Binding = new Binding("Value[3]");
dg.Columns.Add(column);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
<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;
}
}
}
|
标签:Liststring,Dictionary,column,Binding,Dic,Datagrid,Add,new,wpf From: https://www.cnblogs.com/bruce1992/p/16940686.html