【问题标题】:Changing colour of text in a textblock via a trigger通过触发器更改文本块中文本的颜色
【发布时间】:2013-10-27 13:01:04
【问题描述】:

这是我的 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>

代码隐藏(一个 xaml 引用)

public class bob
{

    public string Name
    {
        get;
        set;
    }

    public bool HasErrors
    {
        get;
        set;
    }
 }

基本上我想要做的是,如果 HasErrors 为真,那么我希望名称通过触发器以红色显示。但是我的 xaml 格式不正确。对此有何建议?我也查看了这个链接,但没有太大帮助。
How can I change the Foreground color of a TextBlock with a Trigger?

【问题讨论】:

    标签: c# .net wpf xaml datatrigger


    【解决方案1】:

    你快到了..

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

    【讨论】:

    • 基本上这个值应该是红色的。但这行得通:)谢谢格伦,一旦我从管理员那里获得许可,我就会批准这是一个有效的答案
    • 还要确保您的模型类 (Bob) 实现 INotifyPropertyChanged 并让属性在 setter 中引发事件,以便 UI 知道要更新。
    • @Net Dev 很好发现!谢谢:)
    【解决方案2】:

    在 DataTrigger 中添加一个 setter

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

    【讨论】:

      猜你喜欢
      • 2015-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-02
      相关资源
      最近更新 更多