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>
相关推荐
_extraordinary_6 分钟前
Java SpringMVC(二) --- 响应,综合性练习
java·开发语言
CsharpDev-奶豆哥8 分钟前
ASP.NET中for和foreach使用指南
windows·microsoft·c#·asp.net·.net
@。1241 小时前
对于灰度发布(金丝雀发布)的了解
开发语言·前端
hsjkdhs2 小时前
C++之多层继承、多源继承、菱形继承
开发语言·c++·算法
Full Stack Developme2 小时前
Python Redis 教程
开发语言·redis·python
The Sheep 20233 小时前
WPF自定义路由事件
大数据·hadoop·wpf
阳光雨滴3 小时前
使用wpf用户控件编程落石效果动画
c++·wpf
qq_4924484463 小时前
Jmeter设置负载阶梯式压测场景(详解教程)
开发语言·python·jmeter
cimeo3 小时前
【C 学习】12.2-函数补充
学习·c#
wuty0073 小时前
WPF 调用 ChangeWindowMessageFilterEx 修改指定窗口 (UIPI) 消息筛选器的用户界面特权隔离
wpf·sendmessage·changewindowmessagefilterex·uip·消息筛选器的用户界面特权隔离·window message