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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…