11 April, 2011

How to: Conditional formatting using XAML in WPF

It is often needed to change some UI-property based on a condition of your objects displayed in the UI. An example would be the color of some text (red/green) based on some boolean condition. This is actually quite nifty made in XAML using the Style attributes of XAML-elements.

By letting the Style-binding control the appearance of the TextBlock, you can actually make this change color of the TextBlock based on some condition (a boolean value in this case). Theoretically, you can make any comparison here as long as it makes sense to express this in a textual (string) way.

image    vs.    image

XAML:
This is the XAML-formatting that controls the foreground color of a TextBlock.

   <Window.Resources>
<
Style x:Key="txtRunning" TargetType="TextBlock">
<
Style.Triggers>
<
DataTrigger Binding="{Binding Path=IsRunning}" Value="True">
<
Setter Property="Foreground" Value="Red"/>
<
Setter Property="Text" Value="Running..."/>
</
DataTrigger>

<
DataTrigger Binding="{Binding Path=IsRunning}" Value="False">
<
Setter Property="Foreground" Value="Green"/>
<
Setter Property="Text" Value="Done..."/>
</
DataTrigger>
</
Style.Triggers>
</
Style>

The TextBlock is referencing this Style using this syntax. As you can see above, the text property of the TextBlock; is also changed via the Style (“Running…” vs. “Done…”), hence there is no need to set this property in the below TextBlock XAML-control.

<TextBlock Style="{StaticResource txtRunning}"/>

ViewModel:
The ViewModel to which the above XAML binds is this one.


private bool m_isRunning;
public bool IsRunning
{
get { return m_isRunning; }
set
{
m_isRunning = value;
NotifyPropertyChanged(m => m.IsRunning);
}
}

How easy can it be….?


Technorati Tags:

5 comments:

Ram said...

Simple and Clear. Very Useful post.

Thanks,
Ram.

Izmoto said...

awesome!

a guy behind you said...

thank you man! very clear and useful post!
i've been looking for that for hours!

A yut said...

Very useful post

John Heitmuller said...

Thanks for posting this. I was struggling with this. Something about your example clicked the concept in my head and I got it. Thanks!