Reputation: 2531
I would like to change the background color of a DataGridCell
based on the context value. Currently the the content is text. As shown I'm binding to a data source that generates the columns. I'm not sure how to tell a DataTrigger
to bind to its own value without specifying a tag for each column. I have many columns and would prefer not to have 50 DataTrigger
tags.
Here is my xaml:
<DataGrid x:Name="Grid" ItemsSource="{Binding}">
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Style.Triggers>
<Trigger Property="TextBlock.Text" Value="10"/>
</Style.Triggers>
</Style>
</DataGrid.CellStyle>
</DataGrid>
Ultimately I would like to provide a range of values that would meet the trigger. Such as any value 10 to 20 ( 10 <= value <= 20).
Upvotes: 2
Views: 715
Reputation: 38114
See the following code snippet which shows a data trigger that changes the Background
property of a label
to green when the bound property YourProperty
equals “10”:
<DataGrid x:Name="Grid" ItemsSource="{Binding}">
<DataGrid.CellStyle>
<Style TargetType="DataGridCell">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=YourProperty}" Value="10">
<Setter Property="Label.Background" Value="Green" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.CellStyle>
</DataGrid>
Upvotes: 0
Reputation: 9827
You should use a TemplateColumn as shown below, and in the Loaded event handler, check the condition and take action.
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Area, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" Loaded="TextBox_Loaded"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
private void TextBox_Loaded(object sender, RoutedEventArgs e)
{
var tb = ((TextBox)sender);
if (tb.Text == 10)
{
tb.Background = Brushes.Plum;
}
}
Upvotes: 2