c# - 更改网格中行的背景颜色

标签 c# wpf xaml wpfdatagrid

我正在开发 C#/WPF 应用程序。在其中一个 xaml 屏幕中,我有一个 MS Windows 数据网格,我正在将我的自定义 ListView 集合绑定(bind)到它。此 ListView 集合(即 MyCollection)包含各种产品的价格。该集合的类型为 MyProduct:

public class MyProduct
{
public Int32 Id {get;set;}
public string Name {get;set;}
public Decimal Price {get;set;} 
}

我需要根据价格值更改网格中一行的背景颜色。请问我该如何实现?

我以为我可以使用 RowDataBound 事件处理程序来完成此操作,但我没有在网格中看到此事件处理程序。

最佳答案

DataGridRow 的背景设置成这样:

XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <DataGrid x:Name="dataGrid" Margin="55,29,44,43" ItemsSource="{x:Static local:MainWindow.FakeList}">
            <DataGrid.Resources>
                <Style TargetType="DataGridRow">
                    <Setter Property="Background" Value="{Binding Price, Converter={x:Static local:MyPriceToBackgroundConverter.Instance}}"/>
                </Style>
            </DataGrid.Resources>
        </DataGrid>
    </Grid>
</Window>

窗口类:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    public static List<MyProduct> FakeList
    {
        get
        {
            return new List<MyProduct>
            {
                new MyProduct { Price = 5 },
                new MyProduct { Price = 10 },
                new MyProduct { Price = 20 }
            };
        }
    }
}

转换器:

public class MyPriceToBackgroundConverter : IValueConverter
{
    private static MyPriceToBackgroundConverter instance;
    public static MyPriceToBackgroundConverter Instance
    {
        get
        {
            if (instance == null)
                instance = new MyPriceToBackgroundConverter();
            return instance;
        }
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        decimal price = (decimal)value;
        if (price > 8 && price < 12)
            return Brushes.Red;
        return Brushes.Azure;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // Useless here
        throw new NotImplementedException();
    }
}

关于c# - 更改网格中行的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32145987/

相关文章:

wpf - XAML 触发器作为静态资源

c# - WPF - 项目模板的网格用法

c# - 使用 Microsoft.Web.Administration : Invalid index. 在 IIS7 中以编程方式创建远程站点(HRESULT 异常:0x80070585)

c# - OpenXML 值与 Excel 值不同

C# WPF 应用程序在开发的计算机上运行,​​但不能在其他任何地方运行

c# - 如何制作只允许整数值的文本框?

WPF ControlTemplate 打破样式

wpf - GridView 双击

c# - 用于添加打印机的托管C#方法

c# - 从字符串中获取第二次出现