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

Jonathan Allen picture Jonathan Allen · Jan 27, 2010 · Viewed 11.8k times · Source

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.

Answer

Matt Hamilton picture Matt Hamilton · Jan 27, 2010

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>