tags:

views:

231

answers:

1

I want to do the following:

<TextBlock Text="{Binding Result}">

I want to Color this based on an equality check on Result, what's the view centric way to do this? I remember reading about template selector, is that the right choice here?

example:

Text="Pass" Color="Green"
Text="Fail" Color="Red"

I'd like this to be dynamic so that if Text Changes it is re-evaluated.

+3  A: 

You can use triggers inside a style:

<TextBlock Text="{Binding Result}">
    <TextBlock.Style>
        <Style TargetType="TextBlock">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Result}" Value="Pass">
                    <Setter Property="Foreground" Value="Green" />
                </DataTrigger>

                <DataTrigger Binding="{Binding Result}" Value="Fail">
                    <Setter Property="Foreground" Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>

Alternatively you could create an IValueConverter implementation which converts strings to brushes (according to your rules) and use a binding directly:

<TextBlock
    Text="{Binding Result}"
    Foreground="{Binding Result,Converter={StaticResource my:ResultBrushConverter}} />

I won't go into details for this option because I think the pure-XAML option is the better way to go.

Matt Hamilton
The trigger approach is interesting, I'll start doing it that way to. Is there any disadvantage over the Converter approach?
Carlo
A converter would be a bit more flexible since it's code based. For example, if you needed to change the colour based on a Regex pattern in the text, a converter would make that possible.
Matt Hamilton