让模板化按钮的命令发挥作用
我使用控件模板以简单的方式更改按钮的外观。现在它看起来有所不同,但其行为并不像按钮。实际上有两个问题:
- 按钮的命令永远不会被执行
- 单击按钮后,它显示为被选中(即,椭圆变成丑陋的蓝色矩形)
这是一般想法:
<Button Command="{x:Static commands:...}"
CommandParameter="{Binding}">
<Button.Template>
<ControlTemplate TargetType="Button">
<Ellipse Fill="{Binding ...}"
.../>
</ControlTemplate>
</Button.Template>
</Button>
I've used a control template to change the appearance of a button in a trivial way. It now looks different, but does not behave like a button. There are really two problems:
- The button's command is never executed
- After clicking on the button, it appears selected (i.e., the ellipse turns into an ugly blue rectangle)
Here's the general idea:
<Button Command="{x:Static commands:...}"
CommandParameter="{Binding}">
<Button.Template>
<ControlTemplate TargetType="Button">
<Ellipse Fill="{Binding ...}"
.../>
</ControlTemplate>
</Button.Template>
</Button>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
CommandBinding
无法正常工作。Fill="Green"
,我也没有看到这一点。您可以尝试在Button
上设置FocusVisualStyle="{x:Null}"
。CommandBinding
isn't working properly.Fill="Green"
. You can try settingFocusVisualStyle="{x:Null}"
on theButton
.问题原来是
Fill
绑定到了一个可能为 null 的值。如果Fill
画笔为空而不是透明,则无需单击任何内容,并且不会执行该命令。正如德鲁提到的,使用实心填充时,按钮可以正常工作。要点:如果您想隐藏形状但仍让它响应用户交互,请使用透明画笔,而不是空画笔。
The problem turned out to be that
Fill
was bound to a value that could be null. If theFill
brush is null rather than transparent, then there's nothing to click and the command doesn't get executed. As Drew mentioned, with a solid fill, the button works correctly.Takeaway lesson: if you want to hide your shape but still have it respond to user interaction, use a transparent brush, not a null brush.
我对自定义模板按钮也遇到了类似的问题:
在添加relativesource之前绑定不起作用:
其中custompanel是我的按钮所在的控件。
另外,我在同一面板上有一个简单的按钮,但即使没有relativesource,它也能正常工作。
I had a similar problem with a custom templated button:
The binding didn't work until adding a RelativeSource:
where CustomPanel is a control where my button lies.
Withal I had a simple button on the same panel, but it worked fine even without RelativeSource.