mike
mike

Reputation: 13

WPF User Control XAML Commands

I've got a 3.5 WPF User Control with two buttons and I'd like to be able to bind commands to these buttons via the User Control's xaml.

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

Problem is the above bindings are not working. How can I bind commands to the User control's buttons, two of them, via xaml?

I've got this in the UserControl's code behind and I bind Button1CommandHandler to Button1.Command

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

Upvotes: 0

Views: 870

Answers (1)

svick
svick

Reputation: 244757

You have to make Button1CommandHandler into a dependency property:

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

and then bind your button's Command to it. If you create the button from code, you can bind it like this:

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

Upvotes: 3

Related Questions