zoukankan      html  css  js  c++  java
  • MVVM模式中ICommand在ViewModel中的应用

    MVVM在wpf,sliverlight,window phone中开发中作用很不错,

    最近学习了这个博友的文章,sliverlight中使用mvvm

    这个文章主要记录如何在ViewModel中使用ICommand

    Icommand定义如下:

    namespace System.Windows.Input
    {
    // 摘要:
    // 为命令定义协定。
    public interface ICommand
    {
    // 摘要:
    // 当出现影响是否应执行该命令的更改时发生。
    event EventHandler CanExecuteChanged;

    // 摘要:
    // 定义用于确定此命令是否可以在其当前状态下执行的方法。
    //
    // 参数:
    // parameter:
    // 此命令使用的数据。如果此命令不需要传递数据,则该对象可以设置为 null。
    //
    // 返回结果:
    // 如果此命令可以执行,则为 true;否则为 false。
    bool CanExecute(object parameter);
    //
    // 摘要:
    // 定义在调用此命令时调用的方法。
    //
    // 参数:
    // parameter:
    // 此命令使用的数据。如果此命令不需要传递数据,则该对象可以设置为 null。
    void Execute(object parameter);
    }
    }

    自定义一个RelayCommand类,继承ICommand类

     public class RelayCommand : ICommand
    {
    private Action _handler;

         //Action是一个委托方法,所有的放到都可以传递进来,在Execute中执行。
    public RelayCommand(Action handler)
    {
    this._handler = handler;
    }
    //如果返回false,绑定的控件就会呈现不可使用的效果
    public bool CanExecute(object parameter)
    {
    return true;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
    _handler();
    }
    }


    定义ViewModel,使用ICommand

    public class PersonViewModel
    {
    public List<Person> Human { get; set; }
    public PersonViewModel()
    {
    Human = new Persons().getPerson();
    }

    private ICommand _testCommand;
    public ICommand TestCommand
    {
    get
    {
    return _testCommand = new RelayCommand(TestMethod);//或者执行使用delegate方式写方法代码,不用传方法名
    }
    }

    public void TestMethod()
    {
    MessageBox.Show("hello world");
    }
    }

    在View页面简单的添加一个Button控件

     <Button Name="btnTest" Content="Button Test" Command="{Binding TestCommand}"></Button>

    在View页面的后置代码中

    简单的实例化一个ViewModel

     PersonViewModel personView = new PersonViewModel();

    把当前页面的数据上下文和Viewmodel关联

    this.DataContext = personView;

    然后ViewModel和View就绑定好,ViewModel中的TestCommand命令就和页面上Button按钮绑定到了一起

    运行模拟器,点击按钮就会执行TestCommand命令,弹出“hello world”对话框

    如果控件没有Command属性,那么需要在后置代码中使用代码来绑定Command事件

    如果CanExecute返回false,就会发现按钮控件呈现不可使用的灰色效果

  • 相关阅读:
    ioctl函数用法小记
    scanf函数用法小记
    printf函数用法小记
    REDIS
    lspci 虚拟机网卡对应关系
    vmware安装ubuntu " Intel VT-x 处于禁用状态"
    win10远程桌面配置
    Win10如何彻底禁用小娜?彻底禁用小娜的方法
    为什么Windows7打开项目的方式是灰的不能修改
    以下suse11.3x64可以安装pycrypto-2.6.1
  • 原文地址:https://www.cnblogs.com/zjypp/p/2365180.html
Copyright © 2011-2022 走看看