简体   繁体   中英

Changing colour of text in a textblock via a trigger

Here is my Xaml

 <Window.Resources>
    <sampleData:MainWindow x:Key="DataSource"/>
    <DataTemplate x:Key="bobReferencer">                      
        <TextBlock Text="{Binding Name}" >
            <TextBlock.Style>
                <Style TargetType="TextBlock">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding HasErrors}" Value="true">
                          //what goes in here?
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </TextBlock.Style>
        </TextBlock>                                            
    </DataTemplate>    
</Window.Resources>

Codebehind (the one xaml references)

public class bob
{

    public string Name
    {
        get;
        set;
    }

    public bool HasErrors
    {
        get;
        set;
    }
 }

Basically what i want to do is if the HasErrors is true then i want the Name to appear in Red via the trigger. But my xaml is not properly formed. Any suggestions on this? I also looked into this link but didn't help much.
How can I change the Foreground color of a TextBlock with a Trigger?

You were almost there..

        <Style TargetType="TextBlock">
            <Style.Triggers>
                <DataTrigger Binding="{Binding HasErrors}" Value="true">
                  <Setter Property="Foreground" Value="Red"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>

在DataTrigger中添加设置器

 <Setter Property="Foreground" Value="Red"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM