【问题标题】:WPF- How to apply Style to Multiple controls within a PanelWPF-如何将样式应用于面板中的多个控件
【发布时间】:2011-06-02 09:40:56
【问题描述】:

我需要将样式应用于堆栈面板中的不同控件。它们都是不同的类型,即 TreeView、Listview、ComboBox 等。 有没有办法可以在 StackPanel 级别应用适用于这些控件的样式。 我不想将样式单独应用于这些控件。 有没有办法做到这一点?

谢谢..

【问题讨论】:

    标签: c# wpf styles stackpanel


    【解决方案1】:

    您可以通过使用 StackPanel 资源声明样式来做到这一点。您必须在没有键的情况下声明每个样式,以便它们自动应用于 StackPanel 中的每个目标控件。

    <StackPanel>
         <StackPanel.Resources>
          <!-- Styles declared here will be scoped to the content of the stackpanel  -->
    
          <!-- This is the example of style declared without a key, it will be applied to every TreeView. Of course you'll have to add Setters etc -->
          <Style TargetType="TreeView">
          </Style>
         </StackPanel.Resources>
    
         <!-- Content -->
    
         <!-- This treeview will have the style declared within the StackPanel Resources applied to it-->
         <TreeView />
    </StackPanel>
    

    【讨论】:

    • 在某些问题中,具体取决于您可能希望手动应用语法突出显示的标记,请参阅我的编辑代码或editing-help 中的 "Stack Exchange 添加" 部分.
    【解决方案2】:

    正如 Jean-Louis 所说,您可以在 StackPanel 资源字典中指定 Style,它只会应用于该 StackPanel 中的匹配元素。

    为了使单个Style 匹配您的所有控件,您需要使用所有这些控件的公共基类的TargetType 来指定它,例如Control

    <StackPanel>
      <StackPanel.Resources>
        <Style TargetType="Control">
          <!-- Setters etc here -->
        </Style>
      </StackPanel.Resources>
    
    <!-- Controls here -->
    
    </StackPanel>
    

    【讨论】:

      猜你喜欢
      • 2011-06-08
      • 2012-07-28
      • 1970-01-01
      • 2016-09-18
      • 2015-11-17
      • 2012-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多