c# - 根据其值设置 DataGrid 单元格背景(C#、WPF)

标签 c# wpf xaml datagrid

(围绕这个主题有类似的问题,但没有一个真正符合我的处理方式。)

我想根据每个 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/

相关文章:

c# - 使用 MVVM 的 WPF ComboBox 双向绑定(bind)问题

c# - 组件无法正确缩放

c# - 我应该如何在 .net core 3.0 中绑定(bind)来自 WPF 的 xaml 事件?

c# - 如何在WPF窗口中隐藏关闭按钮?

c# - 使用动态 LINQ 的空表达式

WPF Accordion 垂直对齐错误

c# - 通过 Web 套接字快速发送 Base64 字符串?

xaml - ui没有实时更新

c# - Object.ReferenceEquals 为匹配的字符串返回 true

c# - 如何将字符串 ("1.0000") 转换为 int