【问题标题】:How do you create an OnClick command in WPF MVVM with a programmatically created button?如何使用以编程方式创建的按钮在 WPF MVVM 中创建 OnClick 命令?
【发布时间】:2016-04-28 02:46:33
【问题描述】:

我正在编写一个以编程方式创建几个按钮的 WPF 应用程序。如何为 ViewModel 中的按钮创建 OnClick 命令?我想添加一个命令以使用 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}
                }
            });

【问题讨论】:

    标签: c# wpf mvvm data-binding


    【解决方案1】:

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

    如果是这样,您的视图模型会公开一个命令:

     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 扩展库。

    【讨论】:

      【解决方案2】:

      回答你的第一个问题:

      如何为 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
      }
      

      顺便说一句,安德鲁的解决方案更好。哎呀。

      【讨论】:

        猜你喜欢
        • 2012-05-12
        • 1970-01-01
        • 1970-01-01
        • 2023-03-25
        • 1970-01-01
        • 1970-01-01
        • 2012-09-08
        • 1970-01-01
        相关资源
        最近更新 更多