The following DataTemplate.DataTrigger
makes the age display red if it is equal to 30.
How do I make the age display red if it is greater than 30?
<DataTemplate DataType="{x:Type local:Customer}">
<Grid x:Name="MainGrid" Style="{StaticResource customerGridMainStyle}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="150"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Grid.Column="0" Grid.Row="0" Text="First Name" Margin="5"/>
<TextBlock Grid.Column="1" Grid.Row="0" Text="{Binding FirstName}" Margin="5"/>
<TextBlock Grid.Column="0" Grid.Row="1" Text="Last Name" Margin="5"/>
<TextBlock Grid.Column="1" Grid.Row="1" Text="{Binding LastName}" Margin="5"/>
<TextBlock Grid.Column="0" Grid.Row="2" Text="Age" Margin="5"/>
<TextBlock x:Name="Age" Grid.Column="1" Grid.Row="2" Text="{Binding Age}" Margin="5"/>
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=Age}">
<DataTrigger.Value>30</DataTrigger.Value>
<Setter TargetName="Age" Property="Foreground" Value="Red"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
You could create an
IValueConverter
, which converts an integer to a boolean based on theCutOff
. Then useDataTrigger.Value
ofTrue
(orFalse
, depending on what you are returning).WPF
DataTrigger
s are strictly equality comparers if I remember correctly.So something similar to:
Then use the following XAML.
I'd recommend using an
IValueConverter
to bind to theForeground
element of the AgeTextBlock
and isolating the coloring logic there.Then in the Code:
I believe there is a simpler way of acheiving the goal by using the powers of MVVM and
INotifyPropertyChanged
.With the
Age
property create another property which will be a boolean calledIsAgeValid
. TheIsAgeValid
will simply be an on demand check which does not technically need an theOnNotify
call. How?To get changes pushed to the Xaml, place the
OnNotifyPropertyChanged
forIsAgeValid
within theAge
setter instead.Any binding to
IsAgeValid
will have a notify message sent on anyAge
change which is really what is being looked at.Once setup, of course bind the style trigger for false and true accordingly to the
IsAgeValid
result.