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

发布于 2024-10-01 06:12:44 字数 170 浏览 0 评论 0原文

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

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

但什么也没做

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ら栖息 2024-10-08 06:12:44

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

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

例如,如果您有以下 Style

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

您可以定位所有 Button

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

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

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

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

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

If you have the following Style

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

You can target all Buttons for example

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

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

<Button Style="{StaticResource ControlBaseStyle}" ...>
不…忘初心 2024-10-08 06:12:44

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

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

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}"/>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文