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?

7
  • please go throw this answer stackoverflow.com/questions/643440/…
    – Joby James
    Commented Feb 10, 2016 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. Commented Feb 10, 2016 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
    Commented Feb 10, 2016 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. Commented Feb 10, 2016 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
    Commented Feb 10, 2016 at 13:35

1 Answer 1

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;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.