请参阅下面的问题演示。
<Border xmlns:system="clr-namespace:System;assembly=mscorlib">
<Border.Resources>
<!-- Default style -->
<Style TargetType="DataGridRow">
<Setter Property="Foreground" Value="Red" />
<Setter Property="Visibility" Value="{Binding UnrelatedProperty}" />
</Style>
<Style x:Key="SpecificStyle" TargetType="DataGridRow">
<Setter Property="Background" Value="LightSkyBlue" />
</Style>
</Border.Resources>
<DataGrid RowStyle="{StaticResource SpecificStyle}">
<DataGrid.Columns>
<DataGridTextColumn Header="Column" Binding="{Binding}" />
</DataGrid.Columns>
<system:String>Dummy Item 1</system:String>
<system:String>Dummy Item 2</system:String>
<system:String>Dummy Item 3</system:String>
<system:String>Dummy Item 4</system:String>
</DataGrid>
</Border>
行根据需要显示为蓝色,但我也会收到以下绑定错误:
System.Windows.Data Error: 40 : BindingExpression path error: 'UnrelatedProperty' property not found on 'object' ''String' (HashCode=-121747943)'. BindingExpression:Path=UnrelatedProperty; DataItem='String' (HashCode=-121747943); target element is 'DataGridRow' (Name=''); target property is 'Visibility' (type 'Visibility')
System.Windows.Data Error: 40 : BindingExpression path error: 'UnrelatedProperty' property not found on 'object' ''String' (HashCode=1834567193)'. BindingExpression:Path=UnrelatedProperty; DataItem='String' (HashCode=1834567193); target element is 'DataGridRow' (Name=''); target property is 'Visibility' (type 'Visibility')
System.Windows.Data Error: 40 : BindingExpression path error: 'UnrelatedProperty' property not found on 'object' ''String' (HashCode=-504084967)'. BindingExpression:Path=UnrelatedProperty; DataItem='String' (HashCode=-504084967); target element is 'DataGridRow' (Name=''); target property is 'Visibility' (type 'Visibility')
System.Windows.Data Error: 40 : BindingExpression path error: 'UnrelatedProperty' property not found on 'object' ''String' (HashCode=-1313389031)'. BindingExpression:Path=UnrelatedProperty; DataItem='String' (HashCode=-1313389031); target element is 'DataGridRow' (Name=''); target property is 'Visibility' (type 'Visibility')
对于工作正常的其他网格,需要绑定到UnrelatedProperty。但是在这个网格中,风格根本就不应该使用。看起来默认样式也会部分应用,虽然SpecificStyle没有指定BasedOn,文本也不是红色。
我的问题是:这里发生了什么?我可以通过提供默认样式x:Key="DefaultRowStyle"
来解决问题,并使用以下样式进行应用 - 但我更感兴趣的是了解问题的根源。
<Style TargetType="DataGrid">
<Setter Property="RowStyle" Value="{StaticResource DefaultRowStyle}" />
</Style>
修改
以下是截图: