基于值的WPF Datagrid行颜色
Posted
技术标签:
【中文标题】基于值的WPF Datagrid行颜色【英文标题】:WPF Datagrid row colour based on value 【发布时间】:2016-05-03 04:26:13 【问题描述】:我想根据布尔值更改 DataGrid 的行颜色。我查看了https://***.com/questions/18580612/wpf-datagrid-trigger-row-colour-based-on-value 并以类似的方式尝试了它(在本地定义样式而不是在用户控件的资源中定义它),但是当editable
属性更改时行背景不会改变。我不知道出了什么问题,很乐意尝试一些新事物。
<DataGrid ItemsSource="Binding ReportSampleExaminationList" CanUserDeleteRows="False" PreviewKeyDown="deleteRow" AutoGenerateColumns="False" HorizontalAlignment="Stretch"
RowBackground="Wheat" AlternatingRowBackground="WhiteSmoke" VerticalGridLinesBrush="Transparent" HorizontalGridLinesBrush="Gray">
<DataGrid.CellStyle >
<Style TargetType="DataGridCell">
<Style.Triggers>
<Trigger Property="IsSelected"
Value="True">
<Setter Property="Background"
Value="LightBlue" />
<Setter Property="Foreground"
Value="Black" />
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.CellStyle>
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="Binding Editable" Value="False">
<Setter Property="Background" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridCheckBoxColumn Header="Editable" Binding="Binding Editable"/>
<DataGridTextColumn Header="Probe" Binding="Binding SampleNumber" IsReadOnly="True" />
</DataGrid.Columns>
</DataGrid>
【问题讨论】:
【参考方案1】:如果您从 DataGrid 中取出 RowBackground 和 AlternatingRowBackground,它就可以工作。如果要使用它们,则必须将它们放入 DataGrid 的样式中。
<DataGrid ItemsSource="Binding ReportSampleExaminationList" CanUserDeleteRows="False" PreviewKeyDown="deleteRow" AutoGenerateColumns="False" HorizontalAlignment="Stretch"
VerticalGridLinesBrush="Transparent" HorizontalGridLinesBrush="Gray">
<DataGrid.Style>
<Style TargetType="DataGrid">
<Setter Property="RowBackground" Value="Wheat" />
<Setter Property="AlternatingRowBackground" Value="WhiteSmoke" />
</Style>
</DataGrid.Style>
<DataGrid.CellStyle >
<Style TargetType="DataGridCell">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="LightBlue" />
<Setter Property="Foreground" Value="Black" />
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.CellStyle>
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="Binding Editable" Value="False">
<Setter Property="Background" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridCheckBoxColumn Header="Editable" Binding="Binding Editable,UpdateSourceTrigger=PropertyChanged"/>
<DataGridTextColumn Header="Probe" Binding="Binding SampleNumber" IsReadOnly="True" />
</DataGrid.Columns>
</DataGrid>
【讨论】:
谢谢,完美。我不知道如果在控件的定义中设置了这些属性,我无法覆盖这些属性。以上是关于基于值的WPF Datagrid行颜色的主要内容,如果未能解决你的问题,请参考以下文章