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

标签 c# wpf resourcedictionary

我有一个名为 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 应用于窗口中的所有按钮(即使用它作为按钮的默认样式)。 谁能告诉我怎么做?

最佳答案

您可以在代码隐藏中添加默认样式,如下所示:

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

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

Resources[typeof (Button)] = s;

关于c# - 如何在代码隐藏中将样式添加到 ResourceDictionary,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35315782/

相关文章:

c# - facebook c# sdk 入门

c# - 如何通过 UserControl 参数管理控件的宽度?

wpf - 如何绑定(bind)到 ContentControl 的数据模板中的数据

wpf - ResourceDictionary 源绑定(bind)到模块(用于本地化)

c# - 从 MS Access 应用程序迁移到 .Net 应用程序的优势

c# - .NET Web 浏览器控件和 Dispose()

c# - 环境变量作为 app.config 中的部分路径

WPF - 选项卡中的 xaml 滚动条

c# - 如何在不分配大量内存的情况下显示快速更新的图像?

c# - 如何从 XAML 中定义的 ResourceDictionary 检索 Brush 并将其应用于代码中的元素?