• ICommand分享学习


    优点:逻辑代码和界面设计解耦
    缺点:不是每个控件都有Command属性
    MSDN源码:

    public interface ICommand
    {
    event EventHandler CanExecuteChanged;
    bool CanExecute(object parameter);
    void Execute(object parameter);
    }


    要想实现自定义ICommand就必须实现一个事件和两个方法;
    以下是我自己实现的:
    1.定义Model类:

    public class CustomController : ICommand
        {
            //  CanExecute():判断是否继续执行操作。
           //Execute():执行操作的内容。
           //CanExecuteChanged:当出现影响是否应执行该命令的更改时发生。
    
            private bool canExe;
            public CustomController(bool canexe)
            {
                this.canExe = canexe;
            }
    
            public bool CanExecute(object parameter)
            {
                if (canExe)
                {
                    return true;
                }
                return false;
            }
    
            public event EventHandler CanExecuteChanged;
    
            public void Execute(object parameter)
            {
                if (parameter != null)
                {
                    MessageBox.Show(parameter.ToString());
                 }
                else
                {
                    MessageBox.Show("未设置CommandParameter");
    
                }
            }
        }
                    

    2.定义ViewModel类:

    public class CustomControllerViewModel
    {
    public ICommand CustomCommand { get; set; } //第一个Button命令
    public ICommand CustomCommandTrue { get; set; } //第二个Button命令
    
    public CustomControllerViewModel()
    {
    CustomCommand = new CustomController(false);
    CustomCommandTrue = new CustomController(true);
    }
    }

    3.界面设计MainPage.xaml:

    <Button Content="第一个"
    Height="96"
    HorizontalAlignment="Left"
    Command="{Binding CustomCommand}"
    CommandParameter="第一个Command"
    Margin="-12,433,0,0"
    Name="button1"
    VerticalAlignment="Top"
    Width="200" />
    <Button Command="{Binding CustomCommandTrue}"
    CommandParameter="第二个Command"
    Content="第二个"
    Height="102"
    HorizontalAlignment="Left"
    
    Name="button2"
    VerticalAlignment="Top"
    Width="200"
    Margin="172,430,0,0" />

    4.后台代码MainPage.xaml.cs

    CustomControllerViewModel custom = new CustomControllerViewModel();
    this.DataContext = custom;


    大功告成,这个时候,第一个Button不可用,第二个Button可以用!

  • 相关阅读:
    Asp.net MVC 3实例学习之ExtShop(三)——完成首页
    Asp.net MVC 3实例学习之ExtShop(一)————创建应用并设置开发环境
    JDK里的设计模式
    Linux系统下ssh的相关配置
    简单介绍asp模式与saas模式
    Linux系统中xorg.conf文件简介
    [C++] MurmurHash2的性能
    [C++] 在程序里调用DOS命令
    Android SDK 1.5中文版 (Application基础—1)
    linux系统单网卡绑定双IP的方法
  • 原文地址:https://www.cnblogs.com/Yukang1989/p/2854538.html
Copyright © 2020-2023  润新知