问题描述
<DataGrid x:Name="dataGrid"
ItemsSource="{Binding TestRows}"
HeadersVisibility="All"
GridLinesVisibility="Vertical"
BorderBrush="Gray"
BorderThickness="5"
IsReadOnly="False"
CanUserResizeColumns="False"
CanUserSortColumns = "True"
HorizontalScrollBarVisibility="Visible"
VerticalScrollBarVisibility="Visible"
SelectionMode="Single"
AutoGenerateColumns="True"
AutoGeneratingColumn="dataGrid_AutoGeneratingColumn">
...
...
...
</DataGrid>
自动生成适用于字符串和整数,但是我的数据集合中的项目上也有Dictionary<String,Strategy>
类型的对象。字典对于TestRows
中的每个项目都有相同的键,但是内容不同。
我想要的是让datagrid使用值中的特定属性作为单元格值,为Dictionary中的每个键动态添加自定义DataGridTemplateColumn
。我怀疑我可以为此添加一些内容到dataGrid_AutoGeneratingColumn
中,但是我找不到办法。
我该如何实现上面描述的内容?
解决方法
TestRows是对象的ObservableCollection,集合中每个对象一行。数据网格自动为对象中的每个字符串和整数生成一列,这就是我想要的。但是,我在对象中也有字典。字典在TestRows中的每个对象中都有相同的键,但直到运行时我都不知道这些键是什么。
在设置AutoGeneratingColumn
之后会引发ItemsSource
,以便您可以处理AutoGeneratingColumn
这样的事情:
private void dataGrid_AutoGeneratingColumn(object sender,DataGridAutoGeneratingColumnEventArgs e)
{
if (e.PropertyName == nameof(YourClass.YourDictionaryPropertyName))
{
e.Cancel = true;
DataGrid dataGrid = (DataGrid)sender;
IList sourceCollection = dataGrid.ItemsSource as IList;
MyClass firstItem = sourceCollection?[0] as MyClass;
foreach (var key in firstItem.YourDictionaryPropertyName.Keys)
{
dataGrid.Columns.Add(new DataGridTextColumn { Header = "...",Binding = new Binding($"{nameof(YourClass.YourDictionaryPropertyName)}"[{key}]") });
}
}
}
......,其中YourClass
是“ TestRows”中的一项:
public class YourClass
{
public Dictionary<string,string> YourDictionaryPropertyName { get; }
...
}