【问题标题】:Style.Triggers vs ControlTemplate.TriggersStyle.Triggers 与 ControlTemplate.Triggers
【发布时间】:2015-01-02 08:38:29
【问题描述】:

什么时候应该选择Style.Triggers,什么时候应该选择ControlTemplate.Triggers?使用一个比另一个有什么好处吗?

假设我有这些样式可以达到相同的结果:

<Style TargetType="{x:Type Button}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <ControlTemplate.Triggers>
                    ...
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

<Style TargetType="{x:Type Button}">
    <Setter Property="Template">
        ...
    </Setter>
    <Style.Triggers>
        ...
    </Style.Triggers>
</Style>

【问题讨论】:

    标签: c# wpf xaml styles controltemplate


    【解决方案1】:

    更新来自Background does not change of button C# WPF Windows 8 中的 Button 确实为 IsMouseOver 使用了 ControlTemplate.Trigger,因此在某些情况下,可能需要完全覆盖 ControlTemplate 才能获得所需的功能。因此,在这种情况下,您需要使用 ControlTemplate 触发器而不是 Style 触发器。

    您可能并不总是需要覆盖默认的ControlTemplate。假设您有一个控件,并且当IsMouseOver 为真时,您希望所有 MyTextControl 都有一个蓝色的Foreground,并将其他所有内容保留为默认值。你可以使用这样的东西:

    <Style TargetType="{x:Type MyTextControl}">
        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">
                <Setter Property="Foreground" Value="Blue"/>
            </Trigger>
        </Style.Triggers>
    </Style>
    

    如果你想使用ControlTemplate.Triggers,你需要复制默认的MyTextControlTemplate,否则你最终会没有视觉效果。

    除此之外,我认为唯一的区别是Style.Triggers 的优先级低于ControlTemplate.Triggers (Precedence documentation)。但这只有在您同时使用两种触发器类型时才有意义。

    【讨论】:

    • 对我来说,这不会覆盖默认模板样式
    • @CoolBlue 对,这里的代码将保持默认模板不变。如果您要使用问题中的 代码,您将覆盖默认值。
    • 是的,我的意思是,由于优先级以及自 Windows 8 以来的更改,上述代码不再有效,这是 因为 模板没有被样式覆盖.这些天最好的选择是右键单击控件并按照选项编辑默认样式的副本。 VS2013 开箱即用。
    • @CoolBlue 哦,我现在明白了。这在 Windows 8 中根本不起作用,还是只是存储应用程序?我只能找到thisthis 之类的信息。不幸的是,我没有一台机器可以对此进行测试。
    • 我使用的是 Windows 10 桌面,但无法正常工作。见this answer
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多