WPF用户控制XAML命令
我有一个3.5WPF用户控件,有两个按钮,我希望能够通过用户控件的xaml将命令绑定到这些按钮WPF用户控制XAML命令,wpf,user-controls,binding,command,Wpf,User Controls,Binding,Command,我有一个3.5WPF用户控件,有两个按钮,我希望能够通过用户控件的xaml将命令绑定到这些按钮 x:Usercontrol x:Name:fou Button1Command="{Binding StuffCommandHandler}" Button2Command="{Binding Stuff2CommandHandler}" 问题是上述绑定不起作用。 如何通过xaml将命令绑定到用户控件的两个按钮上 我已经在UserControl的代码中找到了这一点,并将Button1Comma
x:Usercontrol x:Name:fou Button1Command="{Binding StuffCommandHandler}" Button2Command="{Binding Stuff2CommandHandler}"
问题是上述绑定不起作用。
如何通过xaml将命令绑定到用户控件的两个按钮上
我已经在UserControl的代码中找到了这一点,并将Button1CommandHandler绑定到Button1.Command
private ICommand _button1Command;
public ICommand Button1CommandHandler
{
get { return _button1Command; }
set { _button1Command = value; }
}
您必须将
按钮1 CommandHandler
设置为依赖项属性:
public static readonly DependencyProperty ButtonCommandProperty =
DependencyProperty.Register("ButtonCommand", typeof(ICommand), typeof(TwoButtons), new PropertyMetadata(default(ICommand)));
public ICommand ButtonCommand
{
get { return (ICommand)GetValue(ButtonCommandProperty); }
set { SetValue(ButtonCommandProperty, value); }
}
然后将按钮的命令
绑定到它。如果从代码创建按钮,则可以按如下方式绑定它:
button.SetBinding(Button.CommandProperty, new Binding("ButtonCommand") { Source = this });
您必须将
按钮1 CommandHandler
设置为依赖项属性:
public static readonly DependencyProperty ButtonCommandProperty =
DependencyProperty.Register("ButtonCommand", typeof(ICommand), typeof(TwoButtons), new PropertyMetadata(default(ICommand)));
public ICommand ButtonCommand
{
get { return (ICommand)GetValue(ButtonCommandProperty); }
set { SetValue(ButtonCommandProperty, value); }
}
然后将按钮的命令
绑定到它。如果从代码创建按钮,则可以按如下方式绑定它:
button.SetBinding(Button.CommandProperty, new Binding("ButtonCommand") { Source = this });
Button1.Command=ButtonCommand工作得更好,但创建控件时ButtonCommand为null,这是可以理解的。但是,当xaml绑定发生时,Buttoncommand集不会被激发,因此当单击按钮时,StuffCommandHandler永远不会被激发。我遗漏了什么?我在ButtonCommand集合中放了一个断点,它永远不会触发Button1是通过代码动态创建的,如何通过代码(C#)绑定命令?@mike,请参见编辑后的答案。如果在按钮的
命令尚未初始化时,只将ButtonCommand
属性分配给按钮的命令
,则只将null
分配给它,它无法自动知道null
从何而来。您必须使用binding.working更好,Button1.Command=ButtonCommand,但创建控件时ButtonCommand为null,这是可以理解的。但是,当xaml绑定发生时,Buttoncommand集不会被激发,因此当单击按钮时,StuffCommandHandler永远不会被激发。我遗漏了什么?我在ButtonCommand集合中放了一个断点,它永远不会触发Button1是通过代码动态创建的,如何通过代码(C#)绑定命令?@mike,请参见编辑后的答案。如果在按钮的命令尚未初始化时,只将ButtonCommand
属性分配给按钮的命令
,则只将null
分配给它,它无法自动知道null
从何而来。你必须使用绑定。