DEV Community

Cover image for Why WPF Style Triggers and DataTriggers Do Not Apply — Dependency Property Value Precedence
s-iguchi09
s-iguchi09

Posted on Edited on Originally published at s-iguchi09.github.io AI-assisted

Why WPF Style Triggers and DataTriggers Do Not Apply — Dependency Property Value Precedence

A DataTrigger in Style.Triggers should turn a Border pink when HasError is true. The binding resolves, the Output window is clean, and the background stays white. The trigger did fire. Its value simply lost to another one.

This is a short summary. The full article, with BaseValueSource readings for each case on .NET 10, is here:
Why WPF Style Triggers and DataTriggers Do Not Apply — Dependency Property Value Precedence

The cause: a local value

Background="White" written on the element is a local value. Local values outrank style triggers, and style triggers outrank style setters. DependencyPropertyHelper.GetValueSource reports Local on the broken element. Note that {Binding ...} or {DynamicResource ...} written on the element is also a local value.

The fix

Move the default out of the element and into the style:

<Style x:Key="StatusBox" TargetType="Border">
    <Setter Property="Background" Value="White" />
    <Style.Triggers>
        <DataTrigger Binding="{Binding HasError}" Value="True">
            <Setter Property="Background" Value="#FFD4D4" />
        </DataTrigger>
    </Style.Triggers>
</Style>
Enter fullscreen mode Exit fullscreen mode

From code-behind

  • border.Background = ... creates a local value and blocks the trigger again.
  • SetCurrentValue changes the value without creating one, but it does not remove a local value that is already there.
  • ClearValue removes it, along with any binding on that property.

The full article also covers theme triggers that a local Foreground silently disables.

A Japanese version is also available.

Related Articles

Top comments (1)

Collapse
 
topstar_ai profile image
Luis Cruz •

Your explanation of dependency property value precedence is incredibly insightful, especially regarding how it affects WPF triggers. It’s a common pitfall for many developers to overlook the impact of local values on the effectiveness of styles. A practical improvement could be to suggest utilizing a custom method for handling state changes to avoid local value conflicts, which could streamline troubleshooting. If you’re looking for support in refining this part of your project or enhancing the user experience with more robust UI interactions, I’d be happy to discuss a paid collaboration. How have you found the community's response to these common issues?