在MVVM模式中,按鈕Click事件的繫結方法

雲霏霏發表於2014-06-13

  在MVVM模式中,我們將Button的方法寫到ViewModel中,然後繫結到前端介面。通常的做法是寫一個類,繼承ICommand介面,然而如果按鈕比較多的話,就需要寫很多的類,對於後期維護造成很大的不變,微軟提供了一個DelegateCommand類,可以簡化開發。

使用方法如下:

首先生命ViewModel屬性,GetMsg函式,

 public DelegateCommand GetMsg 
      {
         get { return new DelegateCommand(GetMessage); }
      }

在ViewModel中寫方法GetMessage,程式碼如下:

 public void GetMessage(object parameter)
      {
         //Your code...
      }

然後在前端繫結,程式碼如下:

<Button Command="{Binding GetMsg}" IsEnabled="{Binding custom.IsEnable,Mode=TwoWay}"  
CommandParameter="{Binding}" Content="OK" Width="100" Height="32"
HorizontalAlignment="Left" Margin="149,228,0,0" Name="button1"
VerticalAlignment="Top" Canvas.Left="-105" Canvas.Top="3" />

 

其實,DelegateCommand只是一個繼承自ICommand的類,下面我們來寫自己的DelegateCommand類,實現同樣的功能。程式碼如下:

public class DelegateCommand : ICommand
   {
      private Action action;
      private Action<Object> actionT;

      public DelegateCommand(Action action)
      {
         this.action = action;
      }

      public DelegateCommand(Action<Object> action)
      {
         this.actionT = action;
      }

      public bool CanExecute(object parameter)
      {
         return true;
      }

      public event EventHandler CanExecuteChanged;

      public void Execute(object parameter)
      {
         if (action != null)
         {
            action();
         }
         if (actionT != null)
         {
            actionT.Invoke(parameter);
         }
      }
   }

這個類有兩個構造方法,有引數的和無引數的,可以根據自己的需要擴充套件,使用起來非常方便。

 

相關文章