如何有条件地格式化 WPF TextBlock? [英] How do I conditionally format a WPF TextBlock?

查看:28
本文介绍了如何有条件地格式化 WPF TextBlock?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个绑定到字符串的 WPF TextBlock.如果该字符串为空,我希望 TextBlock 以另一种颜色显示警告消息.

I have a WPF TextBlock bound to a string. If that string is empty, I want the TextBlock to display a warning message in another colour.

这在代码中很容易做到,我想知道是否有一个优雅的 WPF 纯 XAML 解决方案?我研究过 Style Triggers,但语法对我来说并不自然.

This is easy to do in code, I was wondering if there was a elegant WPF pure XAML solution for it? I have investigated Style Triggers, but the syntax doesn't come naturally to me.

谢谢!

推荐答案

Daniel 的(略短)回答,因为一些需要的 DataTrigger 东西并不是很简单(比如 {x:Null}):

Adding some details to Daniel's (slightly short) answer as some of the needed DataTrigger stuff is not really trivial (like {x:Null}):

<TextBlock Text="{Binding MyTextProperty}">
    <TextBlock.Style>
        <Style TargetType="{x:Type TextBlock}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding MyTextProperty}" Value="{x:Null}">
                    <Setter Property="Text" Value="Hey, the text should not be empty!"/>
                    <Setter Property="Foreground" Value="Red"/>
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBlock.Style>
</TextBlock>

顺便说一句:这完全是凭记忆做的,没有在 VS 或 Blend 中检查,所以如果那里有错误,请见谅.但是,您应该能够自己整理它们.重要的是想法.祝你好运!

BTW: Did this completely from memory, did not check it in VS or Blend, so please excuse if there are errors in there. However, you should be able to sort them out yourself. What counts is the idea. Good luck!

这篇关于如何有条件地格式化 WPF TextBlock?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆