Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

WPF: DataTrigger on a TextBlock!

0.00/5 (No votes)
8 Sep 2009 1  
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 :

XML
<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:

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

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here