【发布时间】:2011-06-02 09:40:56
【问题描述】:
我需要将样式应用于堆栈面板中的不同控件。它们都是不同的类型,即 TreeView、Listview、ComboBox 等。 有没有办法可以在 StackPanel 级别应用适用于这些控件的样式。 我不想将样式单独应用于这些控件。 有没有办法做到这一点?
谢谢..
【问题讨论】:
标签: c# wpf styles stackpanel
我需要将样式应用于堆栈面板中的不同控件。它们都是不同的类型,即 TreeView、Listview、ComboBox 等。 有没有办法可以在 StackPanel 级别应用适用于这些控件的样式。 我不想将样式单独应用于这些控件。 有没有办法做到这一点?
谢谢..
【问题讨论】:
标签: c# wpf styles stackpanel
您可以通过使用 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>
【讨论】:
正如 Jean-Louis 所说,您可以在 StackPanel 资源字典中指定 Style,它只会应用于该 StackPanel 中的匹配元素。
为了使单个Style 匹配您的所有控件,您需要使用所有这些控件的公共基类的TargetType 来指定它,例如Control
<StackPanel>
<StackPanel.Resources>
<Style TargetType="Control">
<!-- Setters etc here -->
</Style>
</StackPanel.Resources>
<!-- Controls here -->
</StackPanel>
【讨论】: