Monday, April 11, 2011

How to: Conditional 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.

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;


Read more: Claus Konrad Blog