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.
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.
Thanks!
TextBlock is not editable.
The TextBlock control provides flexible text support for UI scenarios that do not require more than one paragraph of text. It supports a number of properties that enable precise control of presentation, such as FontFamily, FontSize, FontWeight, TextEffects, and TextWrapping.
textblock (plural textblocks) The block of pages making up a book, excluding the binding.
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>
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With