DataGrid Row Background Based On Cell Value

后端 未结 1 931
悲哀的现实
悲哀的现实 2020-12-20 17:22

I am currently working on a C# WPF datagrid. I have a DataGrid which has auto generated columns and the code connects to an SQLite Database and creates a dataset and then th

相关标签:
1条回答
  • 2020-12-20 18:04

    You can use a DataTrigger to do this.

    Here is a quick sample. I created a class called Person with the properties Name, Age, and Active.

    public class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public bool Active { get; set; }
    }
    

    In the constructor of the main window, I add 3 Person objects to a list, then bind that list to the DataGrid.

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
    
            List<Person> people = new List<Person>();
            people.Add(new Person() 
            { 
                Name = "John Doe",
                Age = 32,
                Active = true
            });
            people.Add(new Person()
            {
                Name = "Jane Doe",
                Age = 30,
                Active = true
            });
            people.Add(new Person()
            {
                Name = "John Adams",
                Age = 64,
                Active = false
            });
            tblLog.ItemsSource = people;
        }
    }
    

    Then in the XAML for the MainWindow, I create a DataTrigger style as a resource.

    <Window.Resources>
        <Style TargetType="DataGridRow">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Active}" Value="False">
                    <Setter Property="Background" Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    

    What this trigger does is it takes the value from the Active field from the Person object that is in the DataGridRow, and if that value is false, then it turns to background color of the row to red.

    0 讨论(0)
提交回复
热议问题