So, I have this Window with some controls. In the resources section I’ve defined this style:
<Style x:Key="StyleNavBar" TargetType="{x:Type Grid}">
<Style.Triggers>
<DataTrigger Binding="{Binding CurrentTheme, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}">
<DataTrigger.Value>
<theme:WinTheme>WindowsClassic</theme:WinTheme>
</DataTrigger.Value>
<Setter Property="Background" Value="#FFFFFFFF" />
</DataTrigger>
</Style.Triggers>
</Style>
In my Window I define an attached property named ‘CurrentTheme’ which stores (based on an enum) the current theme used system-wide. Here’s the code:
public static readonly DependencyProperty CurrentSystemThemeProperty =
DependencyProperty.RegisterAttached(
"CurrentSystemTheme",
typeof(WinTheme),
typeof(MainWindow),
new UIPropertyMetadata(WinTheme.AeroGlass));
public WinTheme CurrentTheme
{
get
{
return (WinTheme)GetValue(CurrentSystemThemeProperty);
}
set
{
SetValue(CurrentSystemThemeProperty, value);
}
}
Everytime the user changes the system theme, my window receives a callback via WndProc, informing that the theme has changed. And, as you can see, the default value of the CurrentTheme property is WinTheme.AeroGlass. Then I have a grid styled with the style defined above:
<Grid Height="34" Name="grdNavBar" VerticalAlignment="Top" Style="{DynamicResource StyleNavBar}">
My goal is to change the style based on the value of CurrentTheme, but the trigger defined above does not work when the theme changes (it only works with the default value of CurrentTheme, i.e., isn’t reacting to changes in the property).
Any ideas on how to accomplish this?
You’ve passed a different name to
DependencyProperty.RegisterAttachedthan the name you’ve given the property in C#. So the DP system thinks it’s calledCurrentSystemTheme, but your code thinks it’s calledCurrentTheme. Try passingCurrentThemeas the first argument toRegisterAttached.Also, you might want to enable WPF debug log output for data binding (which is on by default in older versions of WPF, but in .NET 4/VS 2010, you need to go and switch it on in the Tools->Options window under Debugging->Output Window). That way, I usually set the WPF Trace Settings -> Data Binding option to All. That way if a data binding fails, you’ll see an error in the Output window. This might help you diagnose why that data trigger is failing.