【问题标题】:How to target all controls (WPF Styles)如何定位所有控件(WPF 样式)
【发布时间】:2011-05-07 01:44:41
【问题描述】:

我可以指定适用于所有元素的样式吗?我试过了

<Style TargetType="Control">
    <Setter Property="Margin" Value="0,5" />
</Style>

但它什么也没做

【问题讨论】:

    标签: wpf user-interface styles


    【解决方案1】:

    您创建的Style 仅针对Control,而不是派生自Control 的元素。当您不设置x:Key 时,它会隐式设置为TargetType,因此在您的情况下为x:Key="{x:Type Control}"

    没有任何直接的方法可以指定Style,它以派生自TargetTypeStyle 的所有元素为目标。你还有其他一些选择。

    如果你有以下Style

    <Style x:Key="ControlBaseStyle" TargetType="{x:Type Control}">
        <Setter Property="Margin" Value="50" />
    </Style>
    

    例如,您可以定位所有Buttons

    <Style TargetType="{x:Type Button}" BasedOn="{StaticResource ControlBaseStyle}"/>
    

    或直接在任何元素上使用样式,例如Button

    <Button Style="{StaticResource ControlBaseStyle}" ...>
    

    【讨论】:

    • 我想知道为什么我的目标类型为 FrameworkElement 的样式没有应用于我的所有控件 - 这回答了这个问题!
    • 真的有那么糟糕吗,我必须为放置在窗口上的所有类型的控件指定样式,而不仅仅是为所有人通用的一些根目录?
    【解决方案2】:

    正如 Fredrik Hedblad 回答的那样,您可以影响从控件继承的所有元素。

    但是你不能为文本块和按钮应用样式,例如,具有相同的样式。

    这样做:

        <Style x:Key="DefaultStyle" TargetType="{x:Type FrameworkElement}">
            <Setter Property="Control.Margin" Value="50"/>
        </Style>
        <Style TargetType="TextBlock" BasedOn="{StaticResource DefaultStyle}"/>
        <Style TargetType="Button" BasedOn="{StaticResource DefaultStyle}"/>
    

    【讨论】:

      猜你喜欢
      • 2021-05-27
      • 2021-02-21
      • 1970-01-01
      • 2019-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多