zoukankan      html  css  js  c++  java
  • 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可以用!

  • 相关阅读:
    04.DRF-开发REST 接口
    03.DRF-设计方法
    02.DRF-认识RESTful
    01.DRF-Web应用模式
    14.Django-xadmin和富文本编辑器
    13.Django-分页
    12.Django-admin
    11.Django-form表单上传文件
    android 基于wifi模块通信开发
    android蓝牙通讯开发(详细)
  • 原文地址:https://www.cnblogs.com/Yukang1989/p/2854538.html
Copyright © 2011-2022 走看看