WPF数据网格中的不同单元格样式取决于ItemsSource中的数据类型

0 wpf datagrid toolkit

我想知道是否有可能根据ItemsSource集合中项目的类型来更改wpf数据网格中列的样式。

我有一个来自wpf工具包的wpf datagrid。网格中的单行应根据ItemsSource集合中项目的类型设置样式。因此,所有项目都是相同的基类类型,但是某些派生类型的列应具有不同的样式。

这可能吗?

谢谢 :-)

小智 5

仅WPF的解决方案:

我参加聚会有点晚了,但是如果其他人正在尝试做这样的事情,那么只有WPF解决方案。没有DataGridColumn类可以直接查找正确的DataTemplate,但是我们可以像这样间接使用ContentPresenter:

<Window.Resources>
    <DataTemplate DataType="{x:Type models:Employee}">
        <Grid>...</Grid>
    </DataTemplate>

    <DataTemplate DataType="{x:Type models:Manager}">
        <Grid>...</Grid>
    </DataTemplate>
</Window.Resources>

<DataGrid ... >
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="MyColumn">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <ContentPresenter Content="{Binding}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>
Run Code Online (Sandbox Code Playgroud)

通过将ContentPresenter夹在CellTemplate内的DataTemplate内,我们可以获得所需的结果。