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 分钟前
JavaScript的Web APIs 入门到实战(day2):事件监听与交互实现,轻松实现网页交互效果(附练习巩固)
开发语言·前端·javascript·学习笔记·web apis 入门到实战
闲人编程16 分钟前
用Python控制硬件:Raspberry Pi项目初体验
开发语言·python·raspberry·pi·codecapsule·控制硬件
cherry--21 分钟前
集合(开发重点)
java·开发语言
半桶水专家27 分钟前
父子组件通信详解
开发语言·前端·javascript
William_cl27 分钟前
C# ASP.NET MVC Model 分类:数据传输对象(DTO)—— 跨层传数的 “精简快递“
c#·asp.net·mvc
鸢尾掠地平40 分钟前
Python中常用内置函数上【含代码理解】
开发语言·python
api_180079054601 小时前
请求、认证与响应数据解析:1688 商品 API 接口深度探秘
java·大数据·开发语言·mysql·数据挖掘
唐古乌梁海1 小时前
【Java】JVM 内存区域划分
java·开发语言·jvm
低调小一1 小时前
Android Gradle 的 compileOptions 与 Kotlin jvmTarget 全面理解(含案例)
android·开发语言·kotlin
zwjapple1 小时前
Kafka 从入门到精通完整指南
c#·linq