基于动态资源的风格

Rob*_*ert 3 c# wpf

似乎不允许这样的事情。任何解决方法?

  <Style x:Key=MyDerivedStyle TargetType="{x:Type Button}"
         BasedOn="{DynamicResource GlobalButtonStyle}" />       

  <Style x:Key="GlobalLabelStyle" TargetType="{x:Type Button}">
Run Code Online (Sandbox Code Playgroud)

我收到错误消息:无法在“样式”类型的“BasedOn”属性上设置“DynamicResourceExtension”。只能在 DependencyObject 的 DependencyProperty 上设置“DynamicResourceExtension”。

如果我将其更改为 StaticResource,则该样式不会出现在我的控件中。

Won*_*ane 6

这里有两个问题:

首先,您的全局样式需要出现在您的派生样式之前(在相同的资源部分中,或者在尝试定义派生样式之前通过合并适当的 ResourceDictionary。

此外,您需要在按钮中明确定义样式:

<Button x:Name="btnOne"
        Style="{StaticResource MyDerivedStyle}"
        Content="Derived" />
Run Code Online (Sandbox Code Playgroud)

请注意,在这种情况下,您不是在创建动态资源(即需要重新加载的资源)。它是静态的,因为用于 BaseOn 的样式需要是静态的。