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>
相关推荐
勘察加熊人25 分钟前
wpf+c#路径迷宫鼠标绘制
开发语言·c#·wpf
OneByOneDotNet28 分钟前
WPF 教程:给 TreeView 添加 SelectedItem 双向绑定支持(MVVM-Friendly)
wpf
小黄人软件1 小时前
C# ini文件全自动界面配置:打开界面时读ini配置到界面各控件,界面上的控件根据ini文件内容自动生成,点保存时把界面各控件的值写到ini里。
开发语言·c#
Android洋芋4 小时前
C语言深度解析:从零到系统级开发的完整指南
c语言·开发语言·stm32·条件语句·循环语句·结构体与联合体·指针基础
bjxiaxueliang4 小时前
一文详解QT环境搭建:Windows使用CLion配置QT开发环境
开发语言·windows·qt
Run_Teenage5 小时前
C语言 【初始指针】【指针一】
c语言·开发语言
苹果.Python.八宝粥5 小时前
Python第七章02:文件读取的练习
开发语言·python
J不A秃V头A5 小时前
Redis批量操作详解
开发语言·redis
牛马baby5 小时前
Java高频面试之并发编程-01
java·开发语言·面试
NaZiMeKiY6 小时前
C++ 结构体与函数
开发语言·c++