Search code examples
wpfxamldatatrigger

How to bind a DataTrigger to a non-bound attribute?


This is not in a template, it is a <Label> in the body of my XAML document. Notice that the Content of the label is set to 'PENDING'. This is monitoring a server connection and at various times the code-behind might change the value of the content to CONNECTED or ERROR. When that happens, I would like for the color of the text to change. I thought this would do it, but it doesn't... all I get is black text.

<Label x:Name="lbl_Connected" Content="PENDING" FontWeight="Bold" Grid.Row="1" Grid.Column="1"  HorizontalAlignment="Left" VerticalAlignment="Center">
    <Label.Style>
        <Style TargetType="Label">
            <Style.Triggers>
                <DataTrigger Binding="{Binding RelativeSource={RelativeSource self}, Path=Content.Value}"  Value="CONNECTED">
                    <Setter Property="Label.Foreground" Value="Green"></Setter>
                </DataTrigger>
                <DataTrigger Binding="{Binding RelativeSource={RelativeSource self}, Path=Content.Value}" Value="PENDING">
                    <Setter Property="Label.Foreground" Value="Yellow"></Setter>
                </DataTrigger>
                <DataTrigger Binding="{Binding RelativeSource={RelativeSource self}, Path=Content.Value}" Value="ERROR">
                    <Setter Property="Label.Foreground" Value="Red"></Setter>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Label.Style>
</Label>

Can someone tell me how I should be doing this?


Solution

  • Just remove the ".Value" part from the Binding's Path, i.e.:

    <DataTrigger Binding="{Binding RelativeSource={RelativeSource self}, Path=Content}" Value="CONNECTED">
        <Setter Property="Label.Foreground" Value="Green"></Setter>
    </DataTrigger>
    

    Anyway if I were you, I would use a Binding in order to set the Label content and a converter to handle the Foreground color.