Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I conditionally format a WPF TextBlock?

Tags:

c#

wpf

xaml

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!

like image 871
Scott Ferguson Avatar asked Apr 26 '10 23:04

Scott Ferguson


People also ask

Is TextBlock editable in WPF?

TextBlock is not editable.

What is TextBlock WPF?

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.

What is TextBlock?

textblock (plural textblocks) The block of pages making up a book, excluding the binding.


1 Answers

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!

like image 155
gehho Avatar answered Sep 21 '22 15:09

gehho