(围绕这个主题有类似的问题,但没有一个真正符合我的处理方式。)
我想根据每个 DataGrid 单元格中的值(整数,从 0 到 3)更改它们的颜色。 目前,我可以通过将鼠标悬停在上方来更改单元格的颜色,方法是:
<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>
此代码将鼠标悬停在单元格上的任何内容更改为“红色”。但是我怎么能根据它的值改变颜色呢?
最佳答案
请引用Change DataGrid cell colour based on values这个答案。
我尝试了使用以下代码在答案中描述的相同方式,它工作正常。
<Window.Resources>
<local:ColorConverter x:Key="NameToBrushConverter"/>
</Window.Resources>
<Grid>
<DataGrid ItemsSource="{Binding SampleList}" AutoGenerateColumns="False">
<DataGrid.Columns>
<!-- Inputs -->
<DataGridTextColumn Width="SizeToCells" Header="Inputs" MinWidth="100" Binding="{Binding RowNum}" >
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Background" Value="{Binding RowNum, Converter={StaticResource NameToBrushConverter}}"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
转换器代码:
public class ColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var input = int.Parse(value.ToString());
switch (input)
{
case 1:
return Brushes.LightGreen;
case 2:
return Brushes.LightBlue;
case 3:
return Brushes.Yellow;
default:
return DependencyProperty.UnsetValue;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
希望这对您有所帮助。
关于c# - 根据其值设置 DataGrid 单元格背景(C#、WPF),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39543187/