mitchwillman
mitchwillman

Reputation: 43

How do you create an OnClick command in WPF MVVM with a programmatically created button?

I am writing a WPF application that programmatically creates a few buttons. How do you create an OnClick command for a button in the ViewModel? I would like to add a command to clear all TextBoxes with the ResetButton.

new StackPanel
            {
                Orientation = Orientation.Horizontal,
                Children =
                {
                    new Button { Name = "SendButton", Content = "Send", MinWidth = 50, MaxHeight = 30, Margin = new Thickness(5), Background = Brushes.DodgerBlue },
                    new Button { Name = "ResetButton", Content = "Reset", MinWidth = 50, MaxHeight = 30, Margin = new Thickness(5), Background = Brushes.DarkRed}
                }
            });

Upvotes: 4

Views: 3529

Answers (2)

pengMiao
pengMiao

Reputation: 334

Answer to your first question:

How do you create an OnClick command for a button in the ViewModel?

You can actually do this to add onclick for a button:

Button button =  new Button { Name = "ResetButton"};
button.Click += button_Click; (button_Click is the name of method)

void button_Click(object sender, RoutedEventArgs e)
{
 //do what you want to do when the button is pressed
}

by the way, Andrew's solution is better. ooaps.

Upvotes: -1

Andrew Shepherd
Andrew Shepherd

Reputation: 45252

Do you have access to the view model as you are creating the Stack Panel?

If so, you have your View Model expose a Command:

 var myViewModel = (MyViewModel)this.DataContext;
 Button sendButton = new Button
                     {
                          Name = "SendButton",
                          Command = myViewModel.SendCommand,
                          // etcd
                     }

And in your view model:

class MyViewModel : INotifyPropertyChanged
{ 

     private class SendCommand : ICommand
     {
          private readonly MyViewModel _viewModel;
          public SendCommand(MyViewModel viewModel) 
          {
              this._viewModel = viewModel; 
          }

          void ICommand.Execute(object parameter)
          {
               _viewModel.Send();
          }

          bool ICommand.CanExecute(object p) 
          {
               // Could ask the view nodel if it is able to execute
               // the command at this moment
               return true;
          }
     }

     public ICommand SendCommand
     {
           get
           {
               return new SendCommand(this);
           }
     }

     internal void Send() 
     {
          // Invoked by your command class
     }
}

This example creates a new class just for this one command. After you've done this more than once you'll probably see a pattern, and wrap it up in a generic utility class. See http://www.wpftutorial.net/delegatecommand.html for an example, or use any of the myriad of WPF extension libraries.

Upvotes: 2

Related Questions