Search code examples
c#.netwpfxamlresourcedictionary

How to change SystemParameters.FocusVisualStyleKey from code behind?


I can change the program's FocusVisualStyle with this:

<Style x:Key="{x:Static SystemParameters.FocusVisualStyleKey}" BasedOn="{StaticResource StyleA}" />

I want to give users an option to change it to a different style, but this doesn't work with an error that it is read-only:

SystemParameters.FocusVisualStyleKey = (Style)Application.Current.Resources["StyleB"];

How can I change it to a different style from code behind?


Solution

  • The FocusVisualStyleKey property is defined on the type SystemParameters. What you do in your XAML code is create a new style in a ResourceDictionary with a key (x:Key) that is equivalent to the value of the FocusVisualStyleKey property. You do not assign a new value to this property, like shown in your code.

    The equivalent in code-behind is adding a style to a resource dictionary with this key. In this example the application resource dictionary, but it applies to any other dictionary, too.

    Application.Current.Resources[SystemParameters.FocusVisualStyleKey] = Application.Current.Resources["StyleB"];