WPF | 跟着视频敲代码7 | 命令Command和通知更改INotifyPropertyChanged
视频地址:https://www.bilibili.com/video/BV1nY411a7T8?p=7
实现效果:
命令Command UI与后台代码分离 当业务变动减少代码修改量
笔记代码:
"Horizontal"> "{Binding Name}" Height="20" Width="200">
////// Demo9.xaml 的交互逻辑 /// 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 { ////// 供前端的Command命令Binding调用 /// 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); } } /// /// 属性变动赋值 为了页面的对应Bing时的联动 /// public class ViewModelBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged([CallerMemberName] string propertyName = "") { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } /// /// 继承ICommand 声明委托Action 使用Execute执行 /// 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(); } } }