【问题标题】:WPF: How do I discard all inherited styles?WPF:如何丢弃所有继承的样式?
【发布时间】:2010-01-26 07:23:35
【问题描述】:

如何告诉控件或控件块不继承任何样式并恢复为默认值?

我需要这个,因为我有一个总体主题很有效,但其中一件真的搞砸了我的设计。

【问题讨论】:

    标签: wpf styles


    【解决方案1】:

    您可以为有问题的 UI 创建自己的容器,并将 InheritanceBehavior 设置为 SkipAllNow(或适合您情况的值):

    using System.Windows;
    using System.Windows.Controls;
    
    public class NoInheritanceContentControl : ContentControl
    {
        public NoInheritanceContentControl()
        {
            InheritanceBehavior = InheritanceBehavior.SkipAllNow;
        }
    }
    

    然后您可以将NoInheritanceContentControl 粘贴到您的可视化树中,其中的任何内容都不会继承样式。

    【讨论】:

    • 这会破坏与外部的绑定并继承 DataContext。在内部(在任何子项中)合并的资源字典不再为 BasedOn="{StaticResource {x:Type ...}}" 提供样式。我修了两天,没有运气。 :/ 如果我遗漏了什么,请告诉我。
    【解决方案2】:

    这很棘手,但你可以试试这个,

    1. 创建 DefaultStyles 资源字典
    2. 创建要保留默认样式的控件的命名样式,如下所示..

      <Style 
          x:Key="DefaultButtonStyle" 
          TargetType="{x:Type Button}"  
          BasedOn="{StaticResource {x:Type Button}}"/>
      
    3. 确保在应用任何主题之前添加此 DefaultStyles,它应该是应用资源中的第一个条目。

    4. 然后您可以在运行时将样式“DefaultButtonStyle”应用于任何控件以保留其默认样式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-03
      • 2017-05-20
      相关资源
      最近更新 更多