Reputation: 393
For example, in xaml I have a DataGrid named PersonList:
<DataGrid Name="PersonList" />
In the codebehind I have a collection of Person:
ObservableCollection<Person> persons = ViewModel.PersonModel;
And then I created a Person DataTable, and binded it to the PersonList in the following way:
PersonDataTable.Columns.Add("Name", typeof(string));
PersonDataTable.Columns.Add("Age", typeof(int));
foreach (var person in persons)
{
if (person != null)
{
PersonDataTable.Rows.Add(
Person.Name,
Person.Age
);
}
}
PersonList.ItemSource = PersonDataTable.AsDataView;
My Question is, how to change the background color of a certain row? For example, change the background color of the row with the person's age > 50
I tried to do it by accessing each row from the PersonList.ItemSource, but I failed and the row is always null:
int count = 0;
foreach (var person in PersonList.ItemSource)
{
var row = PersonList.ItemContainerGenerator.ContainerFromItem(person) as DataGridRow;
if (PersonDataTable.Rows[count].Field<int>(1) > 50)
{
row.Background = Brushes.Gray;
}
count++;
}
Please help, WPF masters :)
Upvotes: 1
Views: 1163
Reputation: 305
Try your logic using converter as shown below:
Here is my AgeAboveLimitConverter file :
using System;
using System.Windows.Data;
namespace DataGridSample.Converter
{
public class AgeAboveLimitConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value != null)
{
return (int)value > 50;
}
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
}
And then in your datagrid xaml file,
add namespace xmlns:converter="clr-namespace:DataGridSample.Converter"
Add Style for DataGridRow in DataGrid,
<Grid>
<Grid.Resources>
<converter:AgeAboveLimitConverter x:Key="AgeConverter"/>
</Grid.Resources>
<DataGrid Name="PersonList">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow" >
<Setter Property="Background" Value="Transparent" />
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Age,Converter={StaticResource AgeConverter}}" Value="true">
<Setter Property="Background" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
</DataGrid>
</Grid>
Upvotes: 1
Reputation: 582
You were almost there. Try the following:
int count = 0;
foreach (var person in PersonList.ItemSource)
{
var row = PersonList.ItemContainerGenerator.ContainerFromItem(person) as DataGridRow;
if (PersonDataTable.Rows[count].Field<int>(1) > 50)
{
row.DefaultCellStyle.BackColor = Color.Gray;
}
count++;
}
Upvotes: 0