【问题标题】:overriding styles defined in generic.xaml results in merged style覆盖 generic.xaml 中定义的样式会导致合并样式
【发布时间】:2015-07-03 11:09:47
【问题描述】:

我有一个控件,其样式在单独的资源字典中定义,并使用 generic.xaml 魔法来应用它。

如果我理解 msdn (https://msdn.microsoft.com/de-de/library/ms750613%28v=vs.110%29.aspx) 上描述的查找机制,generic.xaml 是在应用程序资源之后使用的,但是为 MyWindow 添加样式将导致来自 generic.xaml 的样式 + App 中定义的样式.xaml。

这是我的代码:

Generic.xaml

<ResourceDictionary ...>
   <Style TargetType="{x:Type test:MyWindow}" BasedOn="{StaticResource ResourceKey={x:Type Window}}">
        <Setter Property="Background" Value="Gainsboro" />
        <Setter Property="Title" Value="Default!" />
   </Style>
</ResourceDictionary>

App.xaml

<Application.Resources>
     <ResourceDictionary>
         <Style TargetType="{x:Type test:MyWindow}" BasedOn="{StaticResource ResourceKey={x:Type Window}}">
            <Setter Property="Background" Value="HotPink" />
         </Style>
</Application.Resources>

窗口将具有粉红色背景(来自 application.resource 样式)和“默认!”作为 generic.xaml 样式的标题。

wpf 为什么不停止在应用程序级别搜索样式?

【问题讨论】:

    标签: wpf xaml generic.xaml


    【解决方案1】:

    这是因为默认(主题)样式的处理方式与普通样式不同。

    考虑Dependency Property lookup precedence list

    1. 属性系统强制。
    2. 活动动画。
    3. 局部值。
    4. TemplatedParent 属性。来自 TemplatedParent 的触发器和属性集。
    5. 隐式风格。Style 属性的特殊情况。在这里,Style 属性由任何样式资源填充,其键与该元素的类型匹配。 此查找不会进入主题
    6. 样式触发器。页面或应用程序的样式中的触发器。
    7. 模板触发器。
    8. 样式设置器。
    9. 默认(主题)样式。
    10. 继承。
    11. 依赖属性元数据的默认值。

    当 WPF 决定 MyWindow.Style 的值时,它会遍历优先级列表并确定使用“5. 隐式样式”来分配它。然后它会在 App.xaml 中找到匹配的样式并使用它。如果您在运行时检查 MyWindow 的属性,您确实应该看到 MyWindow.Style 设置为 App.xaml 中的那个。因此,WPF 实际上确实停止在应用程序级别搜索样式。

    只是因为DefaultStyleKeyProperty,默认样式仍然存在于 DependencyProperty 查找列表中,尽管优先级低于 App.xaml 样式。

    在这种情况下,App.xaml 不会设置 Title 属性,因此 DependencyProperty 引擎会回退到 Generic.xaml 中的默认样式以提供值。所以这就是为什么你会得到这种合并的样式行为。

    当然,请注意,这只发生在 Generic.xaml 魔术 is set up properly 时。

    【讨论】:

      猜你喜欢
      • 2010-12-02
      • 2016-02-12
      • 2021-01-01
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多