在MVVM模式中,按鈕Click事件的綁定方法


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

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM