WPF 自定义按钮的命令绑定不起作用
我创建了一个继承 Button 类的自定义按钮。我添加了一些依赖属性,我需要让用户指定按钮的外观。
该按钮看起来很棒,并且依赖属性也按照我的意愿工作。但是,无论我如何尝试,Command 属性都不起作用。
这是我的示例:
public partial class CustomButton : Button
{
... //some dependency property
public CustomButton()
{
...//do some initialization
//I tried checking the Command property over here but it seems like always to be NULL?!
}
}
我的 XAML:
<Button x:Class="CustomButton"
xmlns:.....>
<Button.Resources>
<Style TargetType="Button" x:Key="CustomButtonStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<StackPanel Orientation="Horizontal" Background="Transparent" Height="22">
......more things behind...
</Style>
</Button.Resources>
<Button.Style>
<Style TargetType="{x:Type Button}" BasedOn="{StaticResource CustomButtonStyle}">
</Style>
</Button.Style>
</Button>
我在其他 Windows 控件中使用它,如下所示:
<Controls:CustomButton Command="{Binding NewCommand}" ToolTip="AddNew"/>
该命令总是不被执行,为什么?我错过了什么吗? 请帮忙。谢谢。
I created a custom button that inherits the Button class. I added some dependency property that I need to let the user specify how the button will look like.
The button looks great and the dependency property also worked as I wished. But however, the Command property doesn't work no matter how I try.
Here's my sample:
public partial class CustomButton : Button
{
... //some dependency property
public CustomButton()
{
...//do some initialization
//I tried checking the Command property over here but it seems like always to be NULL?!
}
}
My XAML:
<Button x:Class="CustomButton"
xmlns:.....>
<Button.Resources>
<Style TargetType="Button" x:Key="CustomButtonStyle">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<StackPanel Orientation="Horizontal" Background="Transparent" Height="22">
......more things behind...
</Style>
</Button.Resources>
<Button.Style>
<Style TargetType="{x:Type Button}" BasedOn="{StaticResource CustomButtonStyle}">
</Style>
</Button.Style>
</Button>
I used it in my other windows control like this:
<Controls:CustomButton Command="{Binding NewCommand}" ToolTip="AddNew"/>
The command always not being executed, why? Did I miss out anything?
Please help. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
猜测你的模板只会让实际点击按钮变得困难。作为实验,尝试将根
StackPanel
的背景设置为纯色Red
而不是Transparent
,看看这样是否更容易单击。Guessing your template just makes it difficult to actually click on the button. As an experiment, try setting the background of the root
StackPanel
to solidRed
rather thanTransparent
and see if that makes it easier to click.