56.命令绑定 C#例子 WPF例子

一共是两个控件,绑定了属性和命令。用的是最简做法

创建依赖:

cs 复制代码
    public class RelayCommand : ICommand
    {
        private readonly Action<object> _execute;
        public event EventHandler CanExecuteChanged;

        public RelayCommand(Action<object> execute) => _execute = execute;

        public bool CanExecute(object parameter) => true; // 总是可执行(简化)
        public void Execute(object parameter) => _execute(parameter);
    }

初始化,绑定具体的事件:

cs 复制代码
        public ICommand MyCommand { get; }

        public ViewModel()
        {
            // 这里假设您有一个按钮点击时要执行的方法叫做 ExecuteMethod
            MyCommand = new RelayCommand(param => ExecuteMethod());
        }

        private void ExecuteMethod()
        {
            // 执行您的逻辑
            System.Windows.MessageBox.Show("Command executed!");
            Number += 1;
        }

这里在构造函数中应用了依赖。

绑定到了一个事件,这个事件会在按钮点金时执行。

Mycommand就是前台按钮绑定的属性

ViewModel:

cs 复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using Icommand练习;


namespace Icommand练习
{
    class ViewModel:INotifyPropertyChanged
    {
        public ICommand MyCommand { get; }

        public ViewModel()
        {
            // 这里假设您有一个按钮点击时要执行的方法叫做 ExecuteMethod
            MyCommand = new RelayCommand(param => ExecuteMethod());
        }

        private void ExecuteMethod()
        {
            // 执行您的逻辑
            System.Windows.MessageBox.Show("Command executed!");
            Number += 1;
        }

        private int number;
        public int Number
        {
            get {  return number; }
            set
            {
                number = value;
                OnPropertyChanged(nameof(Number));
            }
        }



        //固定
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

    }

    public class RelayCommand : ICommand
    {
        private readonly Action<object> _execute;
        public event EventHandler CanExecuteChanged;

        public RelayCommand(Action<object> execute) => _execute = execute;

        public bool CanExecute(object parameter) => true; // 总是可执行(简化)
        public void Execute(object parameter) => _execute(parameter);
    }

}

主窗口后台:

cs 复制代码
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Icommand练习
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            DataContext = new ViewModel();
        }
    }
}

XAML:

XML 复制代码
<Window x:Class="Icommand练习.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:Icommand练习"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <TextBox Text="{Binding Number, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Height="23" Margin="10,10,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
        <Button Command="{Binding MyCommand}" Content="Execute" HorizontalAlignment="Left" Margin="10,50,0,0" VerticalAlignment="Top" Width="75"/>
    </Grid>
</Window>
相关推荐
cui__OaO17 分钟前
Linux软件编程--线程
linux·开发语言·线程·互斥锁·死锁·信号量·嵌入式学习
鱼鱼说测试40 分钟前
Jenkins+Python自动化持续集成详细教程
开发语言·servlet·php
艾莉丝努力练剑1 小时前
【洛谷刷题】用C语言和C++做一些入门题,练习洛谷IDE模式:分支机构(一)
c语言·开发语言·数据结构·c++·学习·算法
一阵没来由的风1 小时前
拒绝造轮子(C#篇)ZLG CAN卡驱动封装应用
c#·can·封装·zlg·基础封装·轮子
CHEN5_021 小时前
【Java基础面试题】Java基础概念
java·开发语言
杜子不疼.3 小时前
《Python学习之字典(一):基础操作与核心用法》
开发语言·python·学习
落霞的思绪3 小时前
Java设计模式详细解读
java·开发语言·设计模式
阿巴~阿巴~3 小时前
深入解析C++ STL链表(List)模拟实现
开发语言·c++·链表·stl·list
✎ ﹏梦醒͜ღ҉繁华落℘4 小时前
开发WPF项目时遇到的问题总结
wpf
java1234_小锋4 小时前
一周学会Matplotlib3 Python 数据可视化-绘制自相关图
开发语言·python·信息可视化·matplotlib·matplotlib3