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>
相关推荐
酷爱码2 小时前
如何通过python连接hive,并对里面的表进行增删改查操作
开发语言·hive·python
画个大饼2 小时前
Go语言实战:快速搭建完整的用户认证系统
开发语言·后端·golang
喵先生!3 小时前
C++中的vector和list的区别与适用场景
开发语言·c++
Thomas_YXQ3 小时前
Unity3D Lua集成技术指南
java·开发语言·驱动开发·junit·全文检索·lua·unity3d
xMathematics4 小时前
计算机图形学实践:结合Qt和OpenGL实现绘制彩色三角形
开发语言·c++·qt·计算机图形学·cmake·opengl
程序设计实验室5 小时前
一次小而美的重构:使用 C# 在 Avalonia 中生成真正好看的词云
c#
yuanManGan6 小时前
C++入门小馆: 深入了解STLlist
开发语言·c++
北极的企鹅886 小时前
XML内容解析成实体类
xml·java·开发语言
BillKu6 小时前
Vue3后代组件多祖先通讯设计方案
开发语言·javascript·ecmascript
Python自动化办公社区6 小时前
Python 3.14:探索新版本的魅力与革新
开发语言·python