如何在代码隐藏中将样式添加到 ResourceDictionary

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

我有一个名为 MyButton.xaml 的 ResourceDictionary,其中定义了 x:Type ButtonBase 的样式。

我知道如何使用这个 ResourceDictionary 来定义 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>

我想在代码隐藏中做同样的事情。 现在我可以写

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

但是,我不明白如何将此 buttonBaseStyle 应用到 Window 中的所有按钮(即将其用作按钮的默认样式)。 谁能告诉我怎么做?

您可以像这样在代码隐藏中添加默认样式:

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

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

Resources[typeof (Button)] = s;