上善若水

水善利万物而不争
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

视频地址:https://www.bilibili.com/video/BV1nY411a7T8?p=7

实现效果:   

 

命令Command  UI与后台代码分离 当业务变动减少代码修改量

笔记代码:

  <Grid>
        <StackPanel Orientation="Horizontal">
            <TextBox Text="{Binding Name}" Height="20" Width="200"></TextBox>
            <Button  Command="{Binding ShowCommand}" Height="20" Width="60" Content="测试点击"></Button>
        </StackPanel> 
    </Grid>
   /// <summary>
    /// Demo9.xaml 的交互逻辑
    /// </summary>
    public partial class Demo9 : Window
    {
        public Demo9()
        {
            InitializeComponent();
            this.DataContext = new MainViewModel();
        }
    }
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Input;

namespace WPF03
{
    public class MainViewModel : ViewModelBase
    {
        /// <summary>
        /// 供前端的Command命令Binding调用
        /// </summary>
        public MyCommand ShowCommand { get; set; }
        public MainViewModel()
        {
            ShowCommand = new MyCommand(Show);
        }

        private string name;
        public string Name
        {
            get { return name; }
            set { name = value; OnPropertyChanged(); }
        }
        private string title;
        public string Title
        {
            get { return title; }
            set { title = value; OnPropertyChanged(); }
        }

        public void Show()
        {
            Title = "你点击了按钮 this is Title";
            Name = "你点击了按钮  this is Name";
            MessageBox.Show(Name);
        }
    }
    /// <summary>
    /// 属性变动赋值 为了页面的对应Bing时的联动
    /// </summary>
    public class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public void OnPropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    /// <summary>
    /// 继承ICommand 声明委托Action 使用Execute执行
    /// </summary>
    public class MyCommand : ICommand
    {
        Action executeAction;
        public MyCommand(Action action)
        {
            executeAction = action;
        }
        public event EventHandler CanExecuteChanged;

        public bool CanExecute(object parameter)
        {
            return true;
        }

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

}