CanExecuteChanged 有什么用? [英] What is CanExecuteChanged for?

查看:29
本文介绍了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.

为了使 can execute 模式有用,需要有一些可以用来引发事件的东西.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.

  • 将命令分配给按钮.
  • 按钮订阅可以执行更改的事件.
  • Button execute 可以执行方法并返回 false - 禁用按钮.
  • 您更改可以执行方法所依赖的状态.
  • 您调用 raise 可以在 Prism 命令上执行更改.
  • 可以执行已引发更改的事件.
  • 按钮事件处理程序触发.
  • 按钮调用命令可以执行方法 - 按钮已启用.

示例

在以下基于 Prism 的示例中,我们将 SaveCommand CanExecute 的状态从 false 更改为 true,同时执行 save 命令.调用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天全站免登陆