上善若水

水善利万物而不争
随笔 - 175, 文章 - 0, 评论 - 10, 阅读 - 14万
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

视频地址: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();
        }
    }

}
复制代码

 

相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示