WPF - How do I style a row based on a binding property value?
So I am trying to bind a collection of objects (IList<>) to a WPF datagrid. I would like to make the row background a different color if the 'artist' property is null or empty. I am checking the value stored at开发者_高级运维 the property on the LoadingRow datagrid event. Currently my implementation seems to style all of the rows with an empty or null 'artist' property correctly. The problem is that is also styles the rows where the property is not null or empty in some cases. So some rows are given the red background even though the rows 'artist' property is not null. Can anyone tell me why this could be??
Here is the LoadingRow event:
private void trackGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
Track t = e.Row.DataContext as Track;
if (String.IsNullOrEmpty(t.Artist))
{
e.Row.Background =
new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(255, 255, 125, 125));
}
}
i use a view model in situations like these, it allows binding directly to the colour of the row.
check out the coloured rows sample project on this site
It seems like the easiest way for that to happen would be for the test to get called more than once for the same row, and the second time the value is no longer empty. I can't guess as to why that would happen, but in the meantime, it should be easy to test with:
else
{
e.Row.Background = DependencyProperty.UnsetValue;
}
精彩评论