Reputation: 147
I am using a datagrid and changing the color of the rows according to their conditions and I am performing this programmatically. follow the example as my datagrid is bound to a datatable I load information straight from the datatable
private void UpdateCor () {
gvDados.UpdateLayout ();
for (int i = 0; i <dt.Rows.Count; i ++)
{
var rowContext = (DataGridRow)
gvDados.ItemContainerGenerator.ContainerFromIndex (i);
if (rowContext! = null)
{
if (dt.Rows [i] ["situation"]. ToString (). Equals (1))
rowContext.Background = Brushes.Green;
else
rowContext.Background = Brushes.Red;
}
}
}
With this I can update the color of my grid even though it is not the best method to be approached. my problem is this, whenever I use the scroll to go down or up the bar the colors become outdated. How do I prevent this from happening? that even when I roll the bar the colors stay fixed?
Upvotes: 0
Views: 136
Reputation: 3312
Often, XAML is too simple to express more complicated conditions. I prefer to put the logic which values should use which colors into a converter. This leads to a simpler XAML and much greater flexibility for the converter in C#.
<datagrid.rowstyle>
<style targettype="DataGridRow">
<Setter Property="Background" Value="{Binding RelativeSource={RelativeSource Self},
Path=Item.situation, Converter={StaticResource ValueToBackgroundConverter}}"/>
</style>
</datagrid.rowstyle>
In C#:
class ValueToBackgroundConverter: IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
if (value is int) {
int quantity = (int)value;
if (quantity>=100) return Brushes.White;
if (quantity>=10) return Brushes.WhiteSmoke;
if (quantity>=0) return Brushes.LightGray;
return Brushes.White; //quantity should not be below 0
}
//value is not an integer. Do not throw an exception
// in the converter, but return something that is obviously wrong
return Brushes.Yellow;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
throw new NotImplementedException();
}
}
Formatting the various parts of a WPF Datagrid is notoriously difficult and Microsoft is not providing the necessary information how to do it. Read my article Codeproject: Guide to WPF DataGrid formatting using binding to get a better understanding how to do it easily.
Upvotes: 1
Reputation: 206
This is a similar question to this question. Can be done using datatrigger:
<DataGrid ItemsSource="{Binding YourItemsSource}">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<DataTrigger Binding="{Binding State}" Value="State1">
<Setter Property="Background" Value="Red"></Setter>
</DataTrigger>
<DataTrigger Binding="{Binding State}" Value="State2">
<Setter Property="Background" Value="Green"></Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
</DataGrid>
Upvotes: 1