【问题标题】:Applying a WPF Style to multiple controls将 WPF 样式应用于多个控件
【发布时间】:2011-06-08 04:43:28
【问题描述】:

这个问题可能是重复的,但我在 SO 上找不到。

如果我有一个容器Window、StackPanel、Grid 等,有什么方法可以将Style 应用于其中包含的某种类型的所有控件?

我可以通过使用Container.Resources 并将单个更改设置为TargetType 来应用属性更改,但是当我尝试设置目标的Style 时,我收到一个错误,告诉我无法设置@ 987654328@.

有没有办法在 XAML 中做到这一点?

【问题讨论】:

    标签: .net xaml wpf-controls styles


    【解决方案1】:

    有点,取决于您要设置的内容。如果属性是公共基类的属性,那么可以。 WPF 中的选项也比 Silverlight 多,因为您可以继承样式。比如……

    <Window.Resources>
        <Style x:Key="CommonStyle" TargetType="FrameworkElement">
            <Setter Property="Margin" Value="2" />
        </Style>
        <Style TargetType="StackPanel" BasedOn="{StaticResource CommonStyle}">
        </Style>
        <Style TargetType="Grid" BasedOn="{StaticResource CommonStyle}">
        </Style>
        <Style TargetType="Button" BasedOn="{StaticResource CommonStyle}">
            <Setter Property="Background" Value="LimeGreen" />
        </Style>
    </Window.Resources>
    

    通用样式CommonStyle 将被 3 种隐式样式继承。但是您只能指定所有 FrameworkElement 类共有的属性。您无法在 CommonStyle 中设置 Background,因为 FrameworkElement 不提供 Background 属性。因此,即使 Grid 和 StackPanel 具有 Background(从 Panel 继承),它与 Button 具有的 Background 属性(从 Control 继承)也不同。

    希望这有助于您顺利上路。

    【讨论】:

    • 如果样式没有 x:Key 字段 - 它将应用于该类型的 所有 对象。所以 all StackPanels、Grids & Buttons 都会有这个边距。
    猜你喜欢
    • 1970-01-01
    • 2016-09-18
    • 2012-07-28
    • 1970-01-01
    • 2011-01-29
    • 2015-11-17
    • 1970-01-01
    • 2012-10-16
    • 1970-01-01
    相关资源
    最近更新 更多