【问题标题】:Explicit DataGrid CellStyle Setter is overridden by an implicit cellstyle in the same context?显式 DataGrid CellStyle Setter 被同一上下文中的隐式单元格样式覆盖?
【发布时间】:2025-12-14 10:30:01
【问题描述】:

我对 WPFToolkit (.NET 3.5) 中的 DataGrid 和 .NET 4.0 中的内置版本有一个奇怪的问题:

当使用 CellStyle 的显式设置器创建一个键控 DataGrid 样式到另一个键控样式时,它可以正常工作。但是,当还为DataGridCell 创建无键样式时,它将覆盖DataGrid 样式中的显式CellStyle-setter。这似乎是错误的。这是设计使然还是错误?

<Window.Resources>
    <Style TargetType="DataGridCell">
        <Setter Property="Background" Value="Blue" />
    </Style>
    <Style x:Key="CellStyle1" TargetType="DataGridCell">
        <Setter Property="Background" Value="Green" />
    </Style>
    <Style TargetType="DataGrid">
        <Setter Property="Background" Value="Yellow" />
        <Setter Property="CellStyle" Value="{StaticResource CellStyle1}" />
    </Style>
    <XmlDataProvider x:Key="xmldata" XPath="data/*">
        <x:XData>
            <data xmlns="">
                <item1 />
                <item2 />
                <item3 />
            </data>
        </x:XData>
    </XmlDataProvider>
</Window.Resources>
<Grid>
    <DataGrid ItemsSource="{Binding Source={StaticResource xmldata}}" />
</Grid>

【问题讨论】:

    标签: wpf datagrid overriding styles


    【解决方案1】:

    这行得通:

    <DataGrid ItemsSource="{Binding Source={StaticResource xmldata}}" 
              CellStyle="{StaticResource CellStyle1}" />
    

    似乎Datagrid 的无键样式比DataGridCell 的无键样式弱。这很奇怪,但这是一个有点复杂的问题:Unkeyed mother vs Unkeyed child,谁应该赢?

    【讨论】: