码迷,mamicode.com
首页 > 其他好文 > 详细

在MVVM模式中,按钮Click事件的绑定方法

时间:2014-06-14 15:23:17      阅读:309      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   http   color   

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

这个类有两个构造方法,有参数的和无参数的,可以根据自己的需要扩展,使用起来非常方便。

 

在MVVM模式中,按钮Click事件的绑定方法,布布扣,bubuko.com

在MVVM模式中,按钮Click事件的绑定方法

标签:style   class   blog   code   http   color   

原文地址:http://www.cnblogs.com/lonelyxmas/p/3788099.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!