WPF Command

WPF COMMAND在Windows Presentation Foundation(WPF)框架中是一个设计模式,主要用于实现用户界面(UI)元素和业务逻辑之间的松耦合交互。具体来说,它是MVVM(Model-View-ViewModel)架构中的重要组成部分。

在WPF中,Command是一种行为,允许UI控件(如按钮)的Command属性绑定到一个命令对象,而不是直接绑定到一个方法调用。当用户触发UI事件时(例如点击按钮),相应的命令会被执行,并且该命令可以关联到任何实现了 ICommand 接口的对象,这个对象定义了何时命令可执行以及执行命令时应进行的操作。

通过这种方式,开发者可以在ViewModel层中定义命令并处理业务逻辑,然后在View层中仅声明要绑定的命令,从而极大地增强了代码的可维护性和可测试性。

在WPF应用中,可以通过数据绑定将ICommand实例与UI控件(如Button)的Command属性关联起来 ,**控件的Command属性绑定的主要是方法,**这样在用户与UI交互时,就能够自动调用对应的命令执行逻辑,而无需直接在控件的事件处理器中写入复杂的业务代码。

不管是ICommand还是INotifyPropertyChanged 都必须首先将ViewMode的实例设置为控件或整个界面的 DataContext如,this.DataContext = new MainViewModel();DataContext是UI层与数据逻辑层的桥梁。

ICommand 接口中定义了两个方法和一个属性

  1. Execute 方法:当命令被调用时执行的方法,通常在这里编写处理实际业务逻辑的代码。

    cs 复制代码
    void Execute(object parameter);
  2. CanExecute 方法:判断命令当前是否可以被执行。这个方法返回一个布尔值,视图会根据这个值决定是否使能关联的UI控件。

    cs 复制代码
    bool CanExecute(object parameter);
  3. CanExecuteChanged 事件:当命令的可执行状态改变时触发此事件,视图接收到此事件后会重新检查并更新相关UI控件的状态。

    cs 复制代码
    event EventHandler CanExecuteChanged;
cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace WpfApplication1
{
    public  class MainViewModel
    {

        public MainViewModel()
        {
            ShowMyCommand = new MyCommand(show);
        }

        public MyCommand ShowMyCommand
        {
            set;get;
           
        }
        public void show()
        {
            MessageBox.Show("按钮2被点击了");
        }
    }
}
cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 WpfApplication1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainViewModel();//MainViewModel作为数据源为MainWindow提供上下文
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("按钮被点击了");
        }
    }
}
cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace WpfApplication1
{
    public class MyCommand : ICommand
    {
        public Action ExecuteAction;
        public MyCommand(Action act)
        {
            ExecuteAction += act;
        }
        public event EventHandler CanExecuteChanged;

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

        public void Execute(object parameter)
        {
            ExecuteAction();
        }
    }
}
XML 复制代码
<Window x:Class="WpfApplication1.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:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <StackPanel>
            <Button Content="按钮" Click="Button_Click"/> <!--以事件方式触发-->
            <Button Content="按钮2" Name="btnCommand" Command="{Binding ShowMyCommand}"/><!--已绑定方式实现-->
        </StackPanel>
        
    </Grid>
</Window>
相关推荐
2601_9621741710 小时前
Redis 简介
数据库·redis·wpf
SamChan902 天前
Python+PyMuPDF提取PDF表格并翻译:表格结构检测与双语重建实战
windows·python·ai·pdf·wpf
SamChan902 天前
Python+OpenCV检测PDF翻译后排版偏移:像素级格式一致性验证
python·opencv·ai·pdf·wpf
FuckPatience2 天前
WPF 拿到控件的最初样式,修改获得焦点样式
wpf
主宰者2 天前
【WPF】MainWindow前添加加载窗口,发现加载过程中有白色无内容窗口闪烁一下的解决方案
wpf
Vae_Mars3 天前
WPF中的ControlTemplate(控件模板)
wpf
SamChan903 天前
Python+ReportLab自动生成PDF翻译质量审计报告:从数据到可视化的完整方案
开发语言·python·ai·pdf·wpf
circuitsosk3 天前
多智能体协同在能源数据分析中的实践:分配-执行-校验闭环架构设计
python·数据分析·wpf·能源·并行计算·多智能体系统·agent协作
weixin199701080164 天前
《大促护航:电商API限流与降级,双11峰值500万调用的架构复盘》(附Python源码)
python·架构·wpf
hh9504 天前
gent Plan x DeepSeek Harness:多 Agent 协作场景下的中央编排实践
人工智能·wpf·adg·火山引擎·agent plan·adg成都社区