zoukankan      html  css  js  c++  java
  • 在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);
             }
          }
       }

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

  • 相关阅读:
    mysql5.7 ERROR 1045 (28000): Access denied for user解决方法
    C++ json解决方案
    Gitblit无法查看单个文件解决方案
    git 拉取指定的远程分支(三种方式)
    全栈12
    git commit之后,想撤销commit
    video
    iframe
    git恢复之前版本的两种方法reset、revert
    Eclipse
  • 原文地址:https://www.cnblogs.com/yunfeifei/p/3786396.html
Copyright © 2011-2022 走看看