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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4131034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 22:16:55  来源:igfitidea点击:

How to target all controls (WPF Styles)

wpfuser-interfacestyles

提问by Jiew Meng

Can I specify a style that applies to all elements? I tried

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

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

But it did nothing

但它什么也没做

回答by Fredrik Hedblad

The Styleyou created is only targeting Controland not elements that derive from Control. When you don't set the x:Keyit's implicitly set to the TargetType, so in your case x:Key="{x:Type Control}".

Style您创建仅定位Control,而不是从派生的元素Control。当您不设置x:Key它时,它被隐式设置为TargetType,所以在您的情况下x:Key="{x:Type Control}"

There isn't any direct way to specify a Stylethat targets all elements that derive from the TargetTypeof the Style. You have some other options.

没有任何直接的方法可以指定Style针对所有从 派生的元素TargetTypeStyle。您还有其他一些选择。

If you have the following Style

如果您有以下情况 Style

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

You can target all Buttonsfor example

Buttons例如,您可以针对所有人

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

or use the style directly on any element, e.g. Button

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

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

回答by qazwsx123

As Fredrik Hedblad answered you can effect all elements that inherited from control.

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

But you can't apply style for textblock and button with the same style for example.

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

to do that:

要做到这一点:

    <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}"/>