Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 428
Jonathan Allen Avatar asked Jan 27 '10 04:01

Jonathan Allen


1 Answers

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>
like image 199
Matt Hamilton Avatar answered Sep 23 '22 03:09

Matt Hamilton