更改 ControlTemplate 中的常用颜色
我有一个 ControlTemplate,它在多个元素中使用相同的颜色。 在某些触发器(例如 OnMouseOver)上,我想更改该颜色。 据我所知,我必须为每个元素定义一个设置器来更改其颜色。 有没有一种方法可以引用模板中所有包含的元素都可以访问的共享资源,并且可以通过触发器更改该共享资源,这样我就不必处理每个元素?
这是一个(编造的)示例:
<ControlTemplate x:Key="myTemplate" TargetType="{x:Type Button}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Ellipse Fill="red" Grid.Column="0"/>
<Ellipse Fill="red" Grid.Column="1"/>
<ContentPresenter Grid.ColumnSpan="2" VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
当禁用控件时,我希望省略号为灰色,没有明确设置它们,例如我不想编写
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="_ellipse1" Property="Fill" Value="Grey"/>
<Setter TargetName="_ellipse2" Property="Fill" Value="Grey"/>
</Trigger>
但仅使用一个设置器设置两个椭圆的颜色。
I have a ControlTemplate which uses the same color in multiple elements. On certain triggers (e.g. OnMouseOver) I'd like to change that color. As far as I can see I have to define a setter for every element to change its color. Is there a way to reference a shared resource in the template that all contained elements can access, and which can be changed by a trigger, so I don't have to address each and every element?
Here's an (made up) example:
<ControlTemplate x:Key="myTemplate" TargetType="{x:Type Button}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Ellipse Fill="red" Grid.Column="0"/>
<Ellipse Fill="red" Grid.Column="1"/>
<ContentPresenter Grid.ColumnSpan="2" VerticalAlignment="Center"/>
</Grid>
</ControlTemplate>
When the control is disabled, I want the ellipses to be grey, without setting both of them explicitly, e.g. I don't want to write
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="_ellipse1" Property="Fill" Value="Grey"/>
<Setter TargetName="_ellipse2" Property="Fill" Value="Grey"/>
</Trigger>
but set the color of both ellipses with just one setter.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将触发器放置在省略号(省略号?)的样式上,而不是按钮上。 如果您在按钮上设置 IsEnabled = false,则 IsEnabled 将向下传播。
Place the trigger on a style for the ellipses (ellipsi?) instead of the button. IsEnabled will propagate down if you set IsEnabled = false on the Button.
我认为最好的方法是使用值转换器。 然后你就可以完全避免混乱的触发器。 这是您的示例,但添加了转换器。
这是转换器:
I think the best way to do this is with a value converter. Then you can avoid a messy trigger altogether. Here is your example, but with a converter added.
And here is the converter: