WPF: How do I set the Foreground property of a TextBlock using DataTrigger
Asked Answered
L

2

9

This is my XAML:

<TextBlock Name="SeverityText"
           Grid.Column="1"
           Grid.Row="0"
           Foreground="Red">
    <TextBlock.Triggers>

        <DataTrigger Binding="{Binding Path=Severity}">
            <DataTrigger.Value>
                <sm:Severity>Warning</sm:Severity>
            </DataTrigger.Value>
            <Setter TargetName="SeverityText"
                    Property="Foreground"
                    Value="Yellow" />
        </DataTrigger>
                 <DataTrigger Binding="{Binding Path=Severity}">
            <DataTrigger.Value>
                <sm:Severity>Information</sm:Severity>
            </DataTrigger.Value>
            <Setter TargetName="SeverityText"
                    Property="Foreground"
                    Value="White" />
        </DataTrigger>


    </TextBlock.Triggers>
    <TextBlock>Severity:</TextBlock>
    <TextBlock Text="{Binding Path=Severity}" />
</TextBlock>

This is my error message:

Cannot find the static member 'ForegroundProperty' on the type 'ContentPresenter'.

sm:Severity is an enumeration I imported.

Lylelyles answered 27/1, 2010 at 4:14 Comment(0)
M
13

Your triggers and setters need to be defined in a style, rather than on the TextBlock directly:

<TextBlock>
    <TextBlock.Style>
        <Style TargetType="TextBlock">
            <Style.Triggers>

               <DataTrigger Binding="{Binding Severity}"> 
                   <DataTrigger.Value> 
                       <sm:Severity>Warning</sm:Severity> 
                   </DataTrigger.Value> 
                   <Setter TargetName="SeverityText" 
                           Property="Foreground" 
                           Value="Yellow" /> 
               </DataTrigger>

            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>
Montana answered 27/1, 2010 at 4:26 Comment(2)
Ok, so what are triggers outside of style blocks for?Lylelyles
@Jonathan I haven't used them much myself, but I believe that the Triggers on a control directly are for event triggers, like catching mouse events etc.Montana
S
4

Writing the full path of the property also works:
So

Property="Foreground" -> Property="TextBlock.Foreground"

However as suggested in the previous answer, you get:

System.InvalidOperationException: Triggers collection members must be of type EventTrigger.


...if you don't put it in a style.

Sabadilla answered 16/10, 2012 at 12:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.