gpt4 book ai didi

c# - 如何有条件地格式化 WPF TextBlock?

转载 作者:可可西里 更新时间:2023-11-01 03:05:54 25 4
gpt4 key购买 nike

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

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

谢谢!

最佳答案

Daniel's (slightly short) answer 添加一些细节因为一些需要的 DataTrigger 东西并不是很简单(比如 {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 中检查,所以如果其中有错误,请原谅。但是,您应该能够自己解决它们。重要的是想法。祝你好运!

关于c# - 如何有条件地格式化 WPF TextBlock?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2717758/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com