WPF .Net6框架下, 使用Command 实现控件的事件触发

在WPF项目中,通过实现ICommand接口创建自定义命令类MyICommand,可以在ViewModel中集中管理按钮的点击事件,避免XAML代码后面复杂编辑。在ViewModel实例化时绑定命令,然后在XAML中将按钮的Command属性绑定到ViewModel的对应命令,以此触发和处理点击事件。

概述

在wpf项目中,以button为例,除了click 触发点击事件外,还可以通过command特性来实现。
使用这种方式的好处就是:
不必在xaml对应的cs文件里面进行复杂的编辑,可以将其引导至某个ViewModel.cs文件中进行统一处理。

方法

首先,你需要一个MyICommand类

public class MyICommand : ICommand
    {
        Action _TargetExecuteMethod;
        Func<bool> _TargetCanExecuteMethod;

        public MyICommand(Action executeMethod)
        {
            _TargetExecuteMethod = executeMethod;
        }

        public MyICommand(Action executeMethod, Func<bool> canExecuteMethod)
        {
            _TargetExecuteMethod = executeMethod;
            _TargetCanExecuteMethod = canExecuteMethod;
        }

        public void RaiseCanExecuteChanged()
        {
            CanExecuteChanged(this, EventArgs.Empty);
        }

        bool ICommand.CanExecute(object parameter)
        {

            if (_TargetCanExecuteMethod != null)
            {
                return _TargetCanExecuteMethod();
            }

            if (_TargetExecuteMethod != null)
            {
                return true;
            }

            return false;
        }

        public event EventHandler CanExecuteChanged = delegate { };

        void ICommand.Execute(object parameter)
        {
            if (_TargetExecuteMethod != null)
            {
                _TargetExecuteMethod();
            }
        }
    }

然后,在你的ViewModel.cs文件中,通过构造函数使用它


        public MyICommand YourCommand { get; private set; }
        public ViewModel()
        {
            YourCommand = new MyICommand(OnYourCommand );
          
        }
        private void OnYourCommand ()
        {
        //do sth.
        }

最后,在View.xaml中,绑定并应用你的Command方法

注意:这个需要你的xaml能够访问到你的ViewModel.cs,否则会绑定失败。
以下,是将一个button绑定指令ConnectToggleCommand。

  <Button Name="Btn_ConnectDevice" Margin="150,0,0,0" 
                                Command = "{Binding ConnectToggleCommand}"
                                Content="{Binding BtnConnectAttributes.BtnContent}"
                                IsEnabled="{Binding BtnConnectAttributes.IsEnable}"
                                HorizontalAlignment="Left" VerticalAlignment="Center"
                                Width = "150" Height="Auto" Cursor="Hand">
                </Button>

这样之后,你就可以通过点击这个Button,触发他的Command指令了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值