我有一个名为 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/