如何使用以编程方式创建的按钮在WPF MVVM中创建OnClick命令?

时间:2016-04-28 02:46:33

标签: c# wpf mvvm data-binding

我正在编写一个以编程方式创建几个按钮的WPF应用程序。如何为ViewModel中的按钮创建OnClick命令?我想添加一个命令来清除所有带有ResetButton的TextBox。

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

2 个答案:

答案 0 :(得分:2)

在创建堆栈面板时是否可以访问视图模型?

如果是这样,您的View Model会显示一个命令:

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

在您的视图模型中:

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

此示例仅为此一个命令创建一个新类。在您不止一次完成此操作后,您可能会看到一个模式,并将其包装在通用实用程序类中。有关示例,请参阅http://www.wpftutorial.net/delegatecommand.html,或使用任意无数的WPF扩展库。

答案 1 :(得分:0)

回答你的第一个问题:

  

如何为ViewModel中的按钮创建OnClick命令?

您实际上可以执行此操作来为按钮添加onclick:

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
}
顺便说一句,安德鲁的解决方案更好。 ooaps。