如何定位所有控件(WPF样式)

Jie*_*eng 81 wpf user-interface styles

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

<Style TargetType="Control">
    <Setter Property="Margin" Value="0,5" />
</Style>
Run Code Online (Sandbox Code Playgroud)

但它没有做任何事情

Fre*_*lad 107

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>
Run Code Online (Sandbox Code Playgroud)

Buttons例如,您可以定位所有目标

<Style TargetType="{x:Type Button}" BasedOn="{StaticResource ControlBaseStyle}"/>
Run Code Online (Sandbox Code Playgroud)

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

<Button Style="{StaticResource ControlBaseStyle}" ...>
Run Code Online (Sandbox Code Playgroud)

  • 真的那么糟糕吗,我必须为放置在窗口上的所有类型的控件指定样式,而不仅仅是为所有人通用的一些根东西?? (6认同)

小智 7

正如 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}"/>
Run Code Online (Sandbox Code Playgroud)