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>
From code-behind
-
border.Background = ...creates a local value and blocks the trigger again. -
SetCurrentValuechanges the value without creating one, but it does not remove a local value that is already there. -
ClearValueremoves 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
- Reading WPF Binding Errors and Diagnosing Them with the Output Window
- Binding to a WPF UserControl's Own Dependency Property from Inside the Control
- Selecting and Expanding a WPF TreeView Node from Code, and Why SelectedItem Is Read-Only
- Why StaticResource Changes Are Not Reflected in WPF and How to Fix It
- Formatting Numbers, Currency, and Dates with Binding.StringFormat in WPF
- Why WPF Label Hides Underscores and How to Fix It
- Customising the DatePicker Display Format in WPF
Top comments (1)
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?