Building an application that has a custom 'High Contrast' theme for outdoor use that can be toggled on and off during runtime. This works fine by merging and un-merging a resource dictionary that contains styles like below...
<Style x:Key="{x:Type MenuItem}" TargetType="{x:Type MenuItem}">
<Setter Property="OverridesDefaultStyle" Value="true"/>
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="Template" Value="{StaticResource Theme_MenuItemTemplate}"/>
</Style>
This works great when the usage of a menuitem doesn't specify a style. This isn't realistic though for many situations since there is no way to bind ItemsSource generated children without Styles. For example:
<ContextMenu.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Header" Value="{Binding Path=Name}"/>
<Setter Property="IsCheckable" Value="True"/>
<Setter Property="IsChecked" Value="{Binding Path=Checked}"/>
<EventSetter Event="Checked" Handler="HistoryItem_Checked"/>
</Style>
</ContextMenu.ItemContainerStyle>
Every other post on StackOverflow says you just need to do this...
<Style TargetType="MenuItem" BasedOn="{StaticResource {x:Type MenuItem}}">
<!-- Your overrides -->
</Style>
But this doesn't work for my situation because my BasedOn can and will change at runtime (and of course you can't use DynamicResource extension on the BasedOn property). Doing this in my application currently leads to controls that override getting stuck with their style when the control was loaded while every other control correctly switches without reloading.
So my question...
Is there a way to get DynamicResource extension working for BasedOn or is there another method/hack I can implement to get this to work?
Your Styles should be in a UIElement.Resources tag. This can be dynamically cleared and repopulated.
I do something similar but not as complex like this:
Finally figured out a solution for a
DynamicResouce
forStyle.BasedOn
using anAttachedDependencyProperty
.Here is the fix for
ItemsControl.ItemContainerStyle
(can be easily modified to changeFrameworkElement.Style
)And here is an example...
Here is a modified version that sets the
FrameworkElement.Style
instead in my answer to another post: Setting a local implicit style different from theme-style / alternative to BasedOn DynamicResourceI have a slight improvement for NtscCobalts answer:
You see, it is possible to simply set the base style, when creating a new style. This way the base styles from the base style are automatically in the hierarchy.