我有一个包含多个列的DataGrid。每列包含不同格式的数字。现在我需要为每个单元格应用一个样式,这对于大多数列来说都是完全相同的,但我不知道如何创建共同样式。代码的简化版本如下:
<DataGrid ItemsSource="{Binding Items}">
<DataGrid.Columns>
<DataGridTextColumn Header="First" Binding="{Binding Value1, StringFormat='{}{0:N2} eq'}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding Value1}" Value="0">
<Setter Property="Foreground" Value="{StaticResource Error}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="First" Binding="{Binding Value2, StringFormat='{}{0:N0} fon'}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding Value2}" Value="0">
<Setter Property="Foreground" Value="{StaticResource Error}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn Header="First" Binding="{Binding Value3, StringFormat='{}0x{0:X4}'}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding Value3}" Value="0">
<Setter Property="Foreground" Value="{StaticResource Error}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
对于不同的情况(几个不同的TextBlocks),我已成功使用了对于Text属性我使用StringFormat绑定的方法,并且为了样式目的,我还将相同的值绑定到Tag属性,然后可以在样式中使用用于DataTrigger检查。但我不知道如何直接绑定到Cell的Tag属性。
我想有这样的事情:
<Style TargetType="DataGridCell">
<Style.Triggers>
<DataTrigger Binding="{Binding Tag}" Value="0">
<Setter Property="Foreground" Value="{StaticResource Error}"/>
</DataTrigger>
</Style.Triggers>
</Style>
<DataGrid ItemsSource="{Binding Items}">
<DataGrid.Columns>
<DataGridTextColumn Header="First" CellTag_Binding="{Binding Value1}" Binding="{Binding Value1, StringFormat='{}{0:N2} eq'}"/>
<DataGridTextColumn Header="First" CellTag_Binding="{Binding Value2}" Binding="{Binding Value2, StringFormat='{}{0:N0} fon'}"/>
<DataGridTextColumn Header="First" CellTag_Binding="{Binding Value3}" Binding="{Binding Value3, StringFormat='{}0x{0:X4}'}"/>
</DataGrid.Columns>
</DataGrid>
甚至是这样的事情:
<Style TargetType="DataGridCell">
<Style.Triggers>
<DataTrigger Binding="{Binding Original_Value}" Value="0">
<Setter Property="Foreground" Value="{StaticResource Error}"/>
</DataTrigger>
</Style.Triggers>
</Style>
<DataGrid ItemsSource="{Binding Items}">
<DataGrid.Columns>
<DataGridTextColumn Header="First" Binding="{Binding Value1, StringFormat='{}{0:N2} eq'}"/>
<DataGridTextColumn Header="First" Binding="{Binding Value2, StringFormat='{}{0:N0} fon'}"/>
<DataGridTextColumn Header="First" Binding="{Binding Value3, StringFormat='{}0x{0:X4}'}"/>
</DataGrid.Columns>
</DataGrid>
有可能吗?