MVVM RelayCommand可以执行 [英] MVVM RelayCommand CanExecute

查看:121
本文介绍了MVVM RelayCommand可以执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现带有execute和canExecute部分的RelayCommand. RelayCommand在没有canExecute部分的情况下可以工作,但是当我添加canExecute部分时,该命令将锁定按钮. RelayCommand仅检查CanExecute部分为true时是否可以执行该按钮.一旦canExecute部分变为false,就不再可以单击该按钮,即使应该这样做也是如此.我该如何确保每次我单击按钮时,它都会控制是否可以执行它,并且一旦无法执行就不会永远锁定它?

I'm implementing an RelayCommand with an execute and an canExecute part. The RelayCommand works when it is without the canExecute part, however when I add the canExecute part, the command locks the button. The RelayCommand only checks whether or not the button can be executed as long as the CanExecute part is true. Once the canExecute part becomes false, the button can no longer be clicked, even if it is supposed to. How do I make sure that every time I click on the button it controls whether or not it can be executed, and doesn't lock it forever, once it cannot be executed?

RedoCommand = new RelayCommand(undoRedoController.Redo,undoRedoController.CanRedo);

   public bool CanRedo()
    {
        redoStack.Count();
        redoStack.Any();
        return redoStack.Any();
    }

    public void Redo()
    {
        if (redoStack.Count() <= 0) throw new InvalidOperationException();
        IUndoRedoCommand command = redoStack.Pop();
        undoStack.Push(command);
        command.Execute();
    }


 public class UndoRedoController
{
    private static UndoRedoController controller = new UndoRedoController();

    private readonly Stack<IUndoRedoCommand> undoStack = new Stack<IUndoRedoCommand>();
    private readonly Stack<IUndoRedoCommand> redoStack = new Stack<IUndoRedoCommand>();

    private UndoRedoController() { }

    public static UndoRedoController GetInstance() { return controller; }

推荐答案

由于某些原因,您必须执行以下操作:

For some reason you have to do the following:

public RelayCommand RedoCommand{
     get;
     set;
}

您还可以在设置可选选项之前将其设为私有,具体取决于您的访问级别.那你就

you can also put private before set optional, depending on your access level. Then you do

RedoCommand = new RelayCommand(() => undoRedoController.Redo(), () => undoRedoController.CanRedo());

现在您可以调用RedoCommand.RaiseCanExecuteChanged(); 一切正常.

Now your able to call RedoCommand.RaiseCanExecuteChanged(); And everything works.

这篇关于MVVM RelayCommand可以执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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