5

我有以下情况(简化):

在我的 ResourceDictionary 中,我为 Label 定义了几个命名样式:

<Style
    x:Key="sNormalLabel"
    TargetType="Label" >
    <Setter Property="FontFamily" Value="Verdana" />
    <Setter Property="FontSize" Value="12" />
    <!-- ... -->
</Style>
<Style
    x:Key="sHeaderLabel"
    TargetType="Label"
    BasedOn="{StaticResource sNormalLabel}" >
    <Setter Property="FontSize" Value="16" />
</Style>

然后我通过使用 BasedOn 以一种没有键的样式引用它来将其中一个设为默认值:

<!-- Apply Normal label automatically -->
<Style 
    TargetType="Label"
    BasedOn="{StaticResource sNormalLabel}" />

我认为自动应用常规样式的标签非常方便,这样我知道如果将来我们的设计团队决定使用 Wingdings 之类的东西,整个应用程序(实际上所有应用程序)都非常容易更改共享相同的资源字典)。

创建一个用户控件我想在顶部添加一个带有 sHeaderLabel 样式的标签,所以我应用

Style={StaticResource sHeaderLabel}

在 USerControl XAML 中,在设计器中一切看起来都很好。

但是,当我将 UserControl 添加到 MainWindow 时,标题标签会回到 sNormalLabel 样式(自动应用的样式)。

我认为它与应用样式的顺序有关,UserControl 在创建后由 MainWindow 设置样式,并且 sHeaderLabel 样式被自动覆盖。

这给我留下了几个悬而未决的问题:

  1. 像我一样使用自动应用的样式是否不常见且违反最佳实践?我认为它非常实用,但也许这是错误的方法。
  2. 有没有办法明确排除某些控件应用这些自动样式?我能想到的唯一方法是使用 HeaderLabel 扩展 Label 并应用不同的资源键,以便 HeaderLabel 自动应用 sHeaderLabel 样式。还有其他方法吗?

如果有人对类似的事情有任何实际经验,我将不胜感激。

EDIT: Interestingly, I just realized that I only see these problems with the Font* properties. Setting Foreground/Background brushes differently in Normal/Header style leaves the Label in the UserControl (which is styled to sHeaderLabel) with the CORRECT color. Setting FontWeight to bold in sHeaderLabel has no effect however.

I have also set up TextBox styles in the same way, with a HeaderTExtBox style, and I don't see the problem there either, only with Labels.

Cheers!

./Fredrik

4

2 回答 2

2

一个好的做法可能是避免将基本自动样式应用于标准类型,因为结果可能是不可预测的。

针对最终成为您的问题的问题,一个很好的例子是将样式应用于TextBlock. 此样式将应用于框架LabelButton任何其他可能包含TextBlock不覆盖您正在设置的样式的 a 的控件。

将样式应用于类型的所有实例时,您不能“取消应用”样式,只能用新样式覆盖样式。除非您可以准确预测应用程序中的所有内容(例如为您制作的控件设置样式),否则应避免使用自动样式,而应将x:Key.

于 2013-07-30T16:51:58.017 回答
0

嗯,我想通了。

我也有一个默认样式TextBlock,删除它是一个全局修复。根据MSDN,Label没有TextBlock继承关系,TextBlock也不是派生自,这Control有趣。

可能在内部Label用于TextBlock渲染,我不知道,但显然TextBlock默认样式正在影响Label.

于 2013-07-30T15:02:59.247 回答