【问题标题】:WPF Custom Button's Command Binding doesn't workWPF 自定义按钮的命令绑定不起作用
【发布时间】:2011-05-17 00:36:45
【问题描述】:

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

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

【问题讨论】:

  • 如果您使用普通按钮,它会起作用吗?检查输出窗口是否存在绑定错误
  • 是的,Thomas,如果我使用普通按钮,它就可以工作。
  • 请提供您通过样式应用的完整控制模板。

标签: wpf xaml data-binding custom-controls


【解决方案1】:

猜测您的模板只会使实际点击按钮变得困难。作为一个实验,尝试将根StackPanel 的背景设置为纯色Red 而不是Transparent,看看这样是否更容易点击。

【讨论】:

  • 嗨,我试过了,它不能解决它。仅供参考,问题似乎与命令绑定有关。因为我可以将鼠标悬停在上面,所以我可以单击,并且所有样式似乎都可以正常工作。只是命令似乎没有从父模板传递下来。
猜你喜欢
  • 2015-12-09
  • 2019-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-16
  • 2020-03-06
  • 2018-07-31
相关资源
最近更新 更多