Wednesday, April 25, 2012

Datatrigger not updating control property, WPF

Have you ever noticed that if you try to modify a property in data trigger which is already specified in the control itself then data trigger won't have any effect even when data trigger conditions are met. Consider the following use case in which you've a textbox and a trigger defined on that.
<TextBlock x:Name="My TextBlock"
                  Text="Default Value">
     <TextBlock.Style>
          <Style TargetType={x:Type TextBlock}>
          <Style.Triggers>
                <DataTrigger Binding="{Binding PropertyA}"
                                     value="true">
                <Setter Property="text"
                            value="Updated Value"/>
                </DataTrigger>
          </Style.Triggers>
        </Style>
      </TextBlock.Style>
</TextBlock>
In above example even if PropertyA becomes true then text of the textblock will remain "Default Value" instead of "Updated Value".
Fix: In order to work it properly, you need to specify the "Default Value" in style not with the control. Here is the xaml:
<TextBlock x:Name="My TextBlock">
     <TextBlock.Style>
          <Style TargetType={x:Type TextBlock}>
          <Setter Property="text"
                      value="Default Value" />
               <Style.Triggers>
                <DataTrigger Binding="{Binding PropertyA}"
                                     value="true">
                <Setter Property="text"
                            value="Updated Value"/>
                </DataTrigger>
          </Style.Triggers>
        </Style>
      </TextBlock.Style>
</TextBlock>
 Above xaml will work perfectly. :). Still need to dig up the reason why data trigger behaves this way only.

No comments:

Post a Comment