如何将自定义列类型添加到WPF数据网格?

问题描述

我目前有一个绑定的数据网格,它正在自动生成

<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; }
    ...
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...