Samuel
Samuel

Reputation: 6490

Conditional style based on TextBlock.Text Property?

I am trying to conditionally format a text block depending on the Text property but I can't get it to work:

<Style x:Key="StatusEnumTextStyle" TargetType="TextBlock" >
    <Style.Triggers>
        <DataTrigger Binding="{Binding Text}" Value="InProgress">
            <Setter Property="Foreground" Value="Red" />
        </DataTrigger>
    </Style.Triggers>
</Style>

<TextBlock Text="InProgress" Style="{StaticResource StatusEnumTextStyle}"/>

But I get a binding error:

System.Windows.Data Error: 40 : BindingExpression path error: 'Text' property not found on 'object' ''NotifierViewModel' (HashCode=43600526)'. BindingExpression:Path=Text; DataItem='VM' (HashCode=43600526); target element is 'TextBlock' (Name=''); target property is 'NoTarget' (type 'Object')

Well I see that the trigger tries to get String.Text but how can I use the property of the TextBlock for my trigger?

The background: Basically I want a conditional style based on an Enum called "StatusEnum" but not depending on the changing variable name as I would need two similar styles if one would expect a variable called "CurrentStatusEnum" and another if the var name would be different, e.g "NewStatusEnum". Resorting to matching a property like "Text" would allow me to use same style when ever I use TextBlock

Upvotes: 1

Views: 1181

Answers (1)

Nitin Purohit
Nitin Purohit

Reputation: 18580

Update your DataTrigger Binding as below:

<Style.Triggers>
    <DataTrigger Binding="{Binding Text, RelativeSource={RelativeSource Self}}" Value="InProgress">
        <Setter Property="Foreground" Value="Red" />
    </DataTrigger>
</Style.Triggers>

Upvotes: 3

Related Questions