问题描述
何时应选择Style.Triggers
,何时应选择ControlTemplate.Triggers
?互相使用有什么好处吗?
When should I choose Style.Triggers
and when should I choose ControlTemplate.Triggers
? Are there any benefits using one over another?
说我有这些样式可以达到相同的结果:
Say I have these styles that achieve the same result:
<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>
推荐答案
更新,来自 Windows 8中的Button确实为IsMouseOver使用了ControlTemplate.Trigger,因此在某些情况下ControlTemplate
可能需要完全覆盖才能获得所需的功能.因此,在这种情况下,您需要在样式触发器上使用ControlTemplate触发器.
Update from Background does not change of button C# WPF the Button in windows 8 does use a ControlTemplate.Trigger for IsMouseOver so there are cases where ControlTemplate
may need to be completely overwritten to get the desired functionality. So that would be a case where you need to use ControlTemplate triggers over Style triggers.
您可能并不总是需要覆盖默认的ControlTemplate
.假设您有一个控件,并且希望当IsMouseOver
为true时,所有MyTextControl都具有一个蓝色的Foreground
,并将其他所有内容保留为默认值.您可以使用类似这样的内容:
You may not always need to override the default ControlTemplate
. Say you have a control and you want all the MyTextControl to have a a blue Foreground
when IsMouseOver
is true and leave everything else as default. You could use something like this:
<Style TargetType="{x:Type MyTextControl}">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground" Value="Blue"/>
</Trigger>
</Style.Triggers>
</Style>
如果要使用ControlTemplate.Triggers
,则需要复制默认的MyTextControl
Template
,否则最终将没有视觉效果.
If you wanted to use the ControlTemplate.Triggers
you would need to copy the default MyTextControl
Template
or else you would end up with no visual.
除此之外,我认为唯一的区别是Style.Triggers
的优先级比ControlTemplate.Triggers
(优先级文档).但这仅在同时使用两种触发器类型时才重要.
Aside from that I think the only difference is that Style.Triggers
has a lower precedence than ControlTemplate.Triggers
(Precedence documentation). But that would only matter if you use both trigger types.
这篇关于Style.Triggers与ControlTemplate.Triggers的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!