wpf 如何根据使用数据绑定的属性值设置 DataGrid 的行背景

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18053281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 23:53:10  来源:igfitidea点击:

How to set DataGrid's row Background, based on a property value using data bindings

wpfxamlwpfdatagrid

提问by Tobias Moe Thorstensen

In my XAML code, I want to set the Backgroundcolor of each row, based on a value of the object in one specific row. I have an ObservableCollectionof z, and each of the zhas a property called State. I started out with something like this in my DataGrid:

在我的 XAML 代码中,我想Background根据特定行中对象的值设置每一行的颜色。我有一个ObservableCollectionof z,每个z都有一个名为State. 我从我的以下内容开始DataGrid

<DataGrid.RowStyle>
    <Style TargetType="DataGridRow">
        <Setter Property="Background" 
                Value="{Binding z.StateId, Converter={StaticResource StateIdToColorConverter}}"/>
     </Style>
</DataGrid.RowStyle>

This is a wrong approach because x is not a property in my ViewModel class.

这是一种错误的方法,因为 x 不是我的 ViewModel 类中的属性。

In my ViewModel class I have an ObservableCollection<z>which is the ItemsSourceof this DataGrid, and a SelectedItemof type z.

在我的ViewModel类我有一个ObservableCollection<z>是在ItemsSourceDataGrid,和SelectedItem类型z

I could bind the color to SelectedItem, but this will only change one row in the DataGrid.

我可以将颜色绑定到SelectedItem,但这只会更改DataGrid.

How can I, based on one property change this rows backgroundcolor?

我怎样才能根据一个属性更改此行的背景颜色?

回答by Nitesh

Use a DataTrigger:

使用DataTrigger

<DataGrid ItemsSource="{Binding YourItemsSource}">
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow"> 
            <Style.Triggers>
                <DataTrigger Binding="{Binding State}" Value="State1">
                    <Setter Property="Background" Value="Red"></Setter>
                </DataTrigger>
                <DataTrigger Binding="{Binding State}" Value="State2">
                    <Setter Property="Background" Value="Green"></Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.RowStyle>
</DataGrid>

回答by Vahagn Nahapetyan

The same can be done without DataTriggertoo:

也可以不这样做DataTrigger

 <DataGrid.RowStyle>
     <Style TargetType="DataGridRow">
         <Setter Property="Background" >
             <Setter.Value>
                 <Binding Path="State" Converter="{StaticResource BooleanToBrushConverter}">
                     <Binding.ConverterParameter>
                         <x:Array Type="SolidColorBrush">
                             <SolidColorBrush Color="{StaticResource RedColor}"/>
                             <SolidColorBrush Color="{StaticResource TransparentColor}"/>
                         </x:Array>
                     </Binding.ConverterParameter>
                 </Binding>
             </Setter.Value>
         </Setter>
     </Style>
 </DataGrid.RowStyle>

Where BooleanToBrushConverteris the following class:

BooleanToBrushConverter以下类在哪里:

public class BooleanToBrushConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
            return Brushes.Transparent;

        Brush[] brushes = parameter as Brush[];
        if (brushes == null)
            return Brushes.Transparent;

        bool isTrue;
        bool.TryParse(value.ToString(), out isTrue);

        if (isTrue)
        {
            var brush =  (SolidColorBrush)brushes[0];
            return brush ?? Brushes.Transparent;
        }
        else
        {
            var brush = (SolidColorBrush)brushes[1];
            return brush ?? Brushes.Transparent;
        }
    }

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

回答by NICK_WANTED

In XAML, add and define a RowStyle Property for the DataGridwith a goal to set the Background of the Row, to the Color defined in my Employee Object.

在 XAML 中,为 DataGrid添加并定义一个RowStyle 属性,目的是将 Row背景设置为我的 Employee 对象中定义颜色。

<DataGrid AutoGenerateColumns="False" ItemsSource="EmployeeList">
   <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
             <Setter Property="Background" Value="{Binding ColorSet}"/>
        </Style>
   </DataGrid.RowStyle>

And in my Employee Class

在我的员工班

public class Employee {

    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }

    public string ColorSet { get; set; }

    public Employee() { }

    public Employee(int id, string name, int age)
    {
        Id = id;
        Name = name;
        Age = age;
        if (Age > 50)
        {
            ColorSet = "Green";
        }
        else if (Age > 100)
        {
            ColorSet = "Red";
        }
        else
        {
            ColorSet = "White";
        }
    }
}

This way every Row of the DataGridhas the BackGround Colorof the ColorSetProperty of my Object.

这样,每一个DataGrid的行具有背景色的的ColorSet我的对象的属性