WPF的数据绑定之命令绑定(Command)

创建一个自定义命令类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace MyToDo.NewClass
{
    internal class MyCommand : ICommand
    {
        Action executeAction;
        public MyCommand(Action action)
        {
            executeAction = action;
        }

        public event EventHandler? CanExecuteChanged;

        public bool CanExecute(object? parameter)
        {
            return true;
        }

        public void Execute(object? parameter)
        {
            executeAction();
        }
    }
}

在ViewModel类中添加命令的应用

using MyToDo.NewClass;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace MyToDo
{
    internal class MainViewModel
    {

        public MainViewModel()
        {
            ShowCommand = new MyCommand(ShowMessage);
        }
        public MyCommand ShowCommand { get; set; }

        public void ShowMessage()
        {
            MessageBox.Show("命令按键被点击");
        }
    }
}

在MainWindows中设置其DataContent = New ViewModel();

        public MainWindow()
        {
            InitializeComponent();

            this.DataContext = new MainViewModel();
        }

添加绑定代码

 <Button Command="{Binding ShowCommand}" Width="100" HorizontalAlignment="Left">命令按键</Button>
posted @ 2025-09-24 16:02  鸭子进京赶烤  阅读(22)  评论(0)    收藏  举报