Prevent double-click from double firing a command

前端 未结 14 1823
情书的邮戳
情书的邮戳 2020-12-15 08:34

Given that you have a control that fires a command:

Is there a way to prevent the command from being fired

14条回答
  •  清歌不尽
    2020-12-15 09:29

    I'm using Xamarin and MVVMCross, although is not WPF I think the following solution applies, I created a solution which is viewmodel specific (doesn't deal with platform specific UI) which I think is very handy, using a helper or base class for the viewmodel create a List that keeps track of the commands, something like this:

    private readonly List Commands = new List();
    
            public bool IsCommandRunning(string command)
            {
                return Commands.Any(c => c == command);
            }
    
            public void StartCommand(string command)
            {
                if (!Commands.Any(c => c == command)) Commands.Add(command);
            }
    
            public void FinishCommand(string command)
            {
                if (Commands.Any(c => c == command))  Commands.Remove(command);
            }
    
            public void RemoveAllCommands()
            {
                Commands.Clear();
            }
    

    Add the command in the action like this:

    public IMvxCommand MyCommand
            {
                get
                {
                    return new MvxCommand(async() =>
                    {
                        var command = nameof(MyCommand);
                        if (IsCommandRunning(command)) return;
    
                        try
                        {
                            StartCommand(command);
    
                            await Task.Delay(3000);
                           //click the button several times while delay
                        }
                        finally
                        {
                            FinishCommand(command);
                        }
                    });
                }
            }
    

    The try/finally just ensures the command is always finished.

    Tested it by setting the action async and doing a delay, first tap works second one returns in the condition.

提交回复
热议问题