CanExecuteChanged的作用是什么? [英] What is CanExecuteChanged for?

查看:155
本文介绍了CanExecuteChanged的作用是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用CanExecuteChanged更改可以执行"条件吗?

Can I use CanExecuteChanged to change the "can execute" condition?

否则...用于什么"?

Or else... "for what" its used?

推荐答案

不,您不能使用它来更改可以执行的状态.这是一个事件,参与ICommand模式的对象可以选择收听此事件,例如按钮可能会使用此事件来知道何时重新查询命令状态(通过调用can execute方法)以设置其启用状态.

No you can not use it to change the can execute state. It is an event and objects which participate in the ICommand pattern can choose to listen to this event e.g. a button may use this event to know when to re-query the commands state (by calling the can execute method) to set its enabled state.

为了使可以执行的模式有用,需要使用一些东西来引发事件. Prism的DelegateCommand具有可以调用的方法来手动引发此事件,因此,如果订户已选择加入模式,则订户将重新查询can execute方法.

In order for the can execute pattern to be useful there needs to be something that can be used to raise the event. Prism's DelegateCommand has a method you can call to manually raise this event so subscribers will re-query the can execute method if they have opted into the pattern.

  • 将命令分配给按钮.
  • 订阅的按钮可以执行更改的事件.
  • 按钮execute可以执行方法,并且返回false-禁用按钮.
  • 您更改可执行方法所依赖的状态.
  • 您可以通过Prism命令执行加注操作.
  • 可以执行更改后的事件.
  • 按钮事件处理程序触发.
  • 按钮调用命令可以执行方法-按钮已启用.

示例

在以下基于Prism的示例中,当执行save命令时,我们将SaveCommand CanExecute的状态从false更改为true.对RaiseCanExecuteChanged的调用将引发CanExecuteChanged事件,并且客户端将调用CanExecute方法.实际上,这将使绑定到SaveCommand的保存按钮将其状态从启用更改为禁用,然后再次更改为启用.

In the following Prism based example we change the state of SaveCommand CanExecute from false to true whilst the save command is executing. The call toRaiseCanExecuteChanged will cause the CanExecuteChanged event to be raised, and clients to call the CanExecute method. In practice this would make a Save button that was bound to SaveCommand change its state from enabled to disabled and back to enabled again.

public class BlingViewModel
{
    private DelegateCommand<object> _saveCommand;
    private bool _canSaveExecute = true;

    public ICommand SaveCommand
    {
        get
        {
            if (_saveCommand == null)
            {
                _saveCommand = new DelegateCommand<object>
                    (
                    executeMethod: _ => Save()
                    ,
                    canExecuteMethod: _ => _canSaveExecute
                    );
            }
            return _saveCommand;
        }
    }

    private void Save()
    {
        _canSaveExecute = false;
        _saveCommand.RaiseCanExecuteChanged();

        Console.WriteLine("Saving...");

        _canSaveExecute = true;
        _saveCommand.RaiseCanExecuteChanged();
    }
}

这篇关于CanExecuteChanged的作用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆