2

I have a ResourceDictionary named MyButton.xaml, in which the Style for x:Type ButtonBase is defined.

I know how to use this ResourceDictionary in order to define a Style in XAML.

<Window.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="pack://Application:,,,/Theme;component/MyButton.xaml"/>
        </ResourceDictionary.MergedDictionaries>
        <Style TargetType="Button" BasedOn="{StaticResource {x:Type ButtonBase}}"/>
    </ResourceDictionary>
</Window.Resources>

I'd like to do the same thing in the code-behind. Now I can write

var source = new Uri("Theme;component/MyButton.xaml", UriKind.Relative);
Resources.MergedDictionaries.Add(new ResourceDictionary {Source = source});
var buttonBaseStyle = TryFindResource(typeof (ButtonBase)) as Style;

However, I don't understand how to apply this buttonBaseStyle to all Buttons (i.e. use it as the default style for Buttons) in the Window. Could anyone tell me how?

user4134476
  • 385
  • 4
  • 22
  • please go throw this answer http://stackoverflow.com/questions/643440/override-default-styling-in-wpf-textbox-based-on-presentationframework-aero – Joby James Feb 10 '16 at 13:01
  • Thanks but that's not an answer to my question. I'm asking how to define a default style in code-behind. – user4134476 Feb 10 '16 at 13:19
  • @user4134476 Style btnBaseStyle = TryFindResource(typeof(ButtonBase)) as Style; Style s = new Style(typeof(Button), btnBaseStyle ); Then add it to ressources and you can eat your cake. Note that Controls take a default Style as their Style (if they don't have one defined) when they load, once it's done they don't look for a Style anymore, you have to set it explicitely – nkoniishvt Feb 10 '16 at 13:22
  • @nkoniishvt Thank you very much for your help. I made a new Style s, but is it OK to just add it to the resource dictionary as `Resources.Add("buttonStyle", s);`? If the key is duplicate, this can cause an Argument Exception. – user4134476 Feb 10 '16 at 13:33
  • @user4134476 If you give it a Key then it won't be a default Style that applies by default to all Controls of its TargetType. You could TryFindResource and remove it before adding it – nkoniishvt Feb 10 '16 at 13:35
  • @nkoniishvt I've just found the answer `Resources[typeof (Button)] = new Style(typeof (Button), s);`. Thank you very much again for your swift and appropriate replies. – user4134476 Feb 10 '16 at 13:47
  • @user4134476 No problem. Added the code as answer – nkoniishvt Feb 10 '16 at 13:52

1 Answers1

4

You can add a default Style in code-behind like this:

Style btnBaseStyle = TryFindResource(typeof(ButtonBase)) as Style; 

Style s = new Style(typeof(Button), btnBaseStyle);

Resources[typeof (Button)] = s;
nkoniishvt
  • 2,442
  • 1
  • 14
  • 29