WPF自定义按钮的命令绑定不起作用

时间:2011-05-17 00:36:46

标签: wpf xaml data-binding custom-controls

我创建了一个继承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"/>

命令总是没有被执行,为什么?我错过了什么吗? 请帮忙。感谢。

1 个答案:

答案 0 :(得分:0)

猜测模板只是让实际点击按钮变得困难。作为实验,请尝试将根StackPanel的背景设置为实心Red而不是Transparent,并查看是否可以更轻松地点击。