2011-04-30 88 views
0

我有一个3.5 WPF用户控件,带有两个按钮,我希望能够通过用户控件的xaml将命令绑定到这些按钮。WPF用户控件XAML命令

x:Usercontrol x:Name:fou Button1Command="{Binding StuffCommandHandler}" Button2Command="{Binding Stuff2CommandHandler}" 

问题是上述绑定不起作用。 如何通过xaml将命令绑定到用户控件的按钮,其中两个按钮?

我有了这个在用户控件的代码后面,我绑定Button1CommandHandler到Button1.Command

private ICommand _button1Command; 
    public ICommand Button1CommandHandler 
    { 
     get { return _button1Command; } 
     set { _button1Command = value; } 
    } 

回答

3

你必须要Button1CommandHandler成一个依赖属性:

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); } 
} 

,然后绑定你的按钮的Command。如果你创建的代码按钮,就可以像这样将它绑定:

button.SetBinding(Button.CommandProperty, new Binding("ButtonCommand") { Source = this }); 
+0

更好的工作,Button1.Command = ButtonCommand但在创建控制这是可以理解ButtonCommand为空。但是,当xaml绑定发生时,Buttoncommand集不会被触发,所以当单击hte按钮时,StuffCommandHandler永远不会被触发。我错过了什么? – mike 2011-04-30 18:01:06

+0

我放了ButtonCommand的一个断点,它永远不会触发 – mike 2011-04-30 18:16:46

+0

您必须*将* Button1.Command绑定到'ButtonCommand'。 – svick 2011-04-30 18:55:39