根据其值设置DataGrid单元格背景(C#,WPF) [英] Setting DataGrid cell background based on its value (C#, WPF)
问题描述
(周围有这个问题类似的问题,但没有真正符合我已经走了这件事的方式。)
(There are similar questions around this topic, but none really match the way I've gone about it.)
我想改变每个颜色我DataGrid的细胞基于其内部他们的值(整数,从0到3)。
目前,我可以将鼠标悬停,改变细胞的颜色使用这样的:
I would like to change the colour of each of my DataGrid's cells based on their value inside them (an integer, from 0 to 3). Currently, I am able to change a cell's colour by mousing over, using this:
<DataGrid Name="mapDisplay" ItemsSource="{Binding}" Margin="0,59,10,0">
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Red" />
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.CellStyle>
</DataGrid>
这代码改变任何滑鼠移到单元格红色。但是,我怎么能根据它的值更改颜色?
This code changes any moused over cell to 'Red'. But how could I change the colour according to its value?
推荐答案
如果你的价值范围是有限的,你可以做到这一点的使用下面apparoach XAML。下面的代码假定你的财产的名字是状态:INT
,和你想只改变含有细胞,而不是整行。相反的DisplayIndex
,你可以标题
属性也使用列
名称
If your value-range is finite, you can do it in XAML using below apparoach. Below code assumes your property name is Status : int
, and you want to change only the containing cell,and not entire row. Instead of DisplayIndex
, you can Header
property too to use Column
name.
<DataGrid x:Name="Dgrd">
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Style.Triggers>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding Status}" Value="0"/>
<Condition Binding="{Binding Column.DisplayIndex,RelativeSource={RelativeSource Self}}" Value="1"/>
</MultiDataTrigger.Conditions>
<Setter Property="Background" Value="Blue"/>
</MultiDataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding Status}" Value="1"/>
<Condition Binding="{Binding Column.DisplayIndex,RelativeSource={RelativeSource Self}}" Value="1"/>
</MultiDataTrigger.Conditions>
<Setter Property="Background" Value="Red"/>
</MultiDataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding Status}" Value="2"/>
<Condition Binding="{Binding Column.DisplayIndex,RelativeSource={RelativeSource Self}}" Value="1"/>
</MultiDataTrigger.Conditions>
<Setter Property="Background" Value="Yellow"/>
</MultiDataTrigger>
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding Status}" Value="3"/>
<Condition Binding="{Binding Column.DisplayIndex,RelativeSource={RelativeSource Self}}" Value="1"/>
</MultiDataTrigger.Conditions>
<Setter Property="Background" Value="Olive"/>
</MultiDataTrigger>
</Style.Triggers>
</Style>
</DataGrid.CellStyle>
</DataGrid>
您也可以使用转换
。
这篇关于根据其值设置DataGrid单元格背景(C#,WPF)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!