I\'m trying to set different color for odd rows using XAML.
The datagrid in question has 3 different types of data, which I want to color differently, and simply cha
You can set AlternationCount
on the DataGrid
and then bind to the ancestor DataGridRows
attached property ItemsControl.AlternationIndex
. If the value is "1" you have an odd row number.
Note that when binding to an attached property, you must put parentheses around the attached property. Path=(ItemsControl.AlternationIndex)
will work but Path=ItemsControl.AlternationIndex
won't.
Update
You could also create the property IsOddRow
through an attached behavior. In the behavior you subscribe to LoadingRow
. In the event handler you get the index for the loaded row and check if it is odd or not. The result is then stored in an attached property called IsOddRow
which you can bind to.
To start the behavior add behaviors:DataGridBehavior.ObserveOddRow="True"
to the DataGrid
DataGridBehavior
public class DataGridBehavior
{
#region ObserveOddRow
public static readonly DependencyProperty ObserveOddRowProperty =
DependencyProperty.RegisterAttached("ObserveOddRow",
typeof(bool),
typeof(DataGridBehavior),
new UIPropertyMetadata(false, OnObserveOddRowChanged));
[AttachedPropertyBrowsableForType(typeof(DataGrid))]
public static bool GetObserveOddRow(DataGrid dataGrid)
{
return (bool)dataGrid.GetValue(ObserveOddRowProperty);
}
public static void SetObserveOddRow(DataGrid dataGrid, bool value)
{
dataGrid.SetValue(ObserveOddRowProperty, value);
}
private static void OnObserveOddRowChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
{
DataGrid dataGrid = target as DataGrid;
dataGrid.LoadingRow += (object sender, DataGridRowEventArgs e2) =>
{
DataGridRow dataGridRow = e2.Row;
bool isOddRow = dataGridRow.GetIndex() % 2 != 0;
SetIsOddRow(dataGridRow, isOddRow);
};
}
#endregion // ObserveOddRow
#region IsOddRow
public static DependencyProperty IsOddRowProperty =
DependencyProperty.RegisterAttached("IsOddRow",
typeof(bool),
typeof(DataGridBehavior),
new PropertyMetadata(false));
[AttachedPropertyBrowsableForType(typeof(DataGridRow))]
public static bool GetIsOddRow(DataGridRow dataGridCell)
{
return (bool)dataGridCell.GetValue(IsOddRowProperty);
}
public static void SetIsOddRow(DataGridRow dataGridCell, bool value)
{
dataGridCell.SetValue(IsOddRowProperty, value);
}
#endregion // IsOddRow
}