65.9K
CodeProject is changing. Read more.
Home

WPF: DataTrigger on a TextBlock!

starIconstarIconstarIconemptyStarIconemptyStarIcon

3.00/5 (6 votes)

Sep 8, 2009

GPL3
viewsIcon

66143

So how does one add a DataTrigger to a TextBlock and provide some default value?

How does one add a DataTrigger to a TextBlock and provide some default value? Well, it's actually quite simple, but I have noticed that quite a few people fall down on this one. Firstly, you cannot have set a DataTrigger on anything that is not a Style, ControlTemplate, or DataTemplate. Great, so I will set up a Style for my TextBlock, right? The answer is yes, but you must ensure that you do not override the Text property in your TextBlock, and set the default value in the Style instead like this :

<style x:Key="StatusBlock"
  TargetType="TextBlock"
  BasedOn="{StaticResource {x:Type TextBlock}}">
    <setter Property="Text" Value="Default Text!"/>
</style>
<style .Triggers>
    <datatrigger 
      Binding="{Binding Path=CurrentView.IsRefreshing}"
      Value="true">
          <setter Property="TextBlock.Text"
                Value="Status: Refreshing! (please wait)..."/>
    </datatrigger>
</style>

Your TextBlock should be defined with the text not set, like this:

<textblock Style="{StaticResource StatusBlock}"/>