Skip to main content
 首页 » 编程设计

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

2024年02月05日14youxin

我正在开发 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(); 
    } 
}