【问题标题】:How to add a Style to a ResourceDictionary in code-behind如何在代码隐藏中向 ResourceDictionary 添加样式
【发布时间】:2016-02-10 12:49:54
【问题描述】:

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

【问题讨论】:

  • 请去抛出这个答案stackoverflow.com/questions/643440/…
  • 谢谢,但这不是我问题的答案。我在问如何在代码隐藏中定义默认样式。
  • @user4134476 样式 btnBaseStyle = TryFindResource(typeof(ButtonBase)) 作为样式;样式 s = new Style(typeof(Button), btnBaseStyle );然后将其添加到资源中,您就可以吃蛋糕了。请注意,控件在加载时将默认样式作为其样式(如果它们没有定义),一旦完成,它们就不再寻找样式,您必须明确设置它
  • @nkoniishvt 非常感谢您的帮助。我制作了一个新的 Style s,但是可以将其添加到资源字典中作为 Resources.Add("buttonStyle", s); 吗?如果键是重复的,这可能会导致参数异常。
  • @user4134476 如果你给它一个 Key,那么它就不会是一个默认样式,默认情况下适用于其 TargetType 的所有控件。您可以 TryFindResource 并在添加之前将其删除

标签: c# wpf resourcedictionary


【解决方案1】:

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

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

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

Resources[typeof (Button)] = s;

【讨论】:

    猜你喜欢
    • 2011-05-16
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    • 2016-11-14
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多