2016-04-28 15 views
4

プログラムでいくつかのボタンを作成するWPFアプリケーションを作成しています。 ViewModelのボタンのOnClickコマンドをどのように作成しますか? ResetButtonですべてのTextBoxをクリアするコマンドを追加したいと思います。プログラムで作成されたボタンを使用して、WPF MVVMでOnClickコマンドを作成するにはどうすればよいですか?

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

スタックパネルを作成するときにビューモデルにアクセスできますか?

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

この例では、この1つのだけのコマンドのために新しいクラスを作成します。これを複数回実行した後は、おそらくパターンが表示され、一般的なユーティリティクラスにまとめられます。例については、http://www.wpftutorial.net/delegatecommand.htmlを参照するか、無数のWPF拡張ライブラリを使用してください。あなたの最初の質問に

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。

関連する問題