user4134476
user4134476

Reputation: 385

How to add a Style to a ResourceDictionary in code-behind

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?

Upvotes: 2

Views: 2150

Answers (1)

nkoniishvt
nkoniishvt

Reputation: 2521

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;

Upvotes: 4

Related Questions