MVVM RelayCommand CanExecute [英] MVVM RelayCommand CanExecute

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

问题描述

我正在实现一个带有 execute 和 canExecute 部分的 RelayCommand.RelayCommand 在没有 canExecute 部分时工作,但是当我添加 canExecute 部分时,命令会锁定按钮.RelayCommand 只检查按钮是否可以执行,只要 CanExecute 部分为真.一旦 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 CanExecute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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