2012-03-25 9 views
0

MainWindowのボタンコマンドにICommandプロパティをバインドしようとしています。しかし、それは動作していません。 これは私が試したサンプルコードです。WPFのMainWindowクラスからICommandをバインドする方法は?

C#コード:

public partial class MainWindow : Window 
{ 
    private ICommand _StartButtonCommand; 

    public ICommand StartButtonCommand 
    { 
     get{ return this._StartButtonCommand;} 
     set 
     { 
      if (this._StartButtonCommand!=value) 
      { 
       this._StartButtonCommand = value; 
      } 
     } 
    } 
    public MainWindow() 
    { 
     InitializeComponent(); 
     this.StartButtonCommand = new ReplayCommand(new Action<object>(startButtonCommandEx)); 
    } 
    private void startButtonCommandEx(object obj) 
    { 
     MessageBox.Show("Done"); 
    } 

    protected class ReplayCommand : ICommand 
    { 
     private Action<object> _action; 

     public ReplayCommand(Action<object> action) 
     { 
      this._action = action; 
     } 
     public bool CanExecute(object parameter) 
     { 
      return true; 
     } 

     public event EventHandler CanExecuteChanged; 

     public void Execute(object parameter) 
     { 
      try 
      { 
       if (parameter!=null) 
       { 
        this._action(parameter); 
       } 
      } 
      catch (Exception ex) 
      { 

       MessageBox.Show(ex.Message, "AutoShutdown", MessageBoxButton.OK, MessageBoxImage.Error); 
      } 
     } 
    } 

にXAML:

<Button x:Name="buttonStrat" Content="Start" HorizontalAlignment="Left" Width="84.274" Height="39.246" Command="{Binding StartButtonCommand, ElementName=window}"/> 

は実際に私がs why i am writing ICommand in MainWindow Class. I donはトン、これは正しい方法であるか知っているUI要素をDataGridViewののSelectedItemプロパティまたはICommandのを使用して、他のUIプロパティにアクセスしたいです間違った道。私はそれを試して、私は成功ではありません。それが間違っている場合は、アドバイスをしてください私は正しい方法とそれを行う方法です。

ありがとうございました。

答えて

1

まず、あなたはボタンの上にDataContextを設定しなかった:

buttonStrat.DataContext = this; 

とXAMLを使用してこの:

Command="{Binding StartButtonCommand}" 

また、あなたのコードを短くするために、あなたはにあなたの財産を変えることができますこれは:

public ICommand StartButtonCommand 
{ 
    get { return new ReplayCommand(new Action<object>(startButtonCommandEx)); } 
} 
関連する問題