我的按钮正在执行两次或更多次

时间:2015-07-03 10:29:38

标签: c# wpf mvvm windows-phone

当有人双击某个按钮时,我试图避免两次或多次执行异步任务。

当我的应用有延迟时,我等待_navigation.ShowMyButton();将去两次或更多次。

    private readonly ICommand MyButton;
    private bool? canExecuteMyButton { get; set; }

    public MyViewModel()
    {
        this.MyButton = new Command((nothing) =>
            {
                GoToMyButton();
            }, this.CanExecuteMyButton);
    }

    private async void GoToMyButton()
    {
        canExecuteMyButton = false;
        await _navigation.ShowMyButton();
        canExecuteMyButton = true;
    }

    private bool CanExecuteMyButton(object state)
    {
        if (canExecuteMyButton == null)
            return true;

        return (bool)canExecuteMyButton;
    }

1 个答案:

答案 0 :(得分:0)

这应该更好:

private async void GoToMyButton()
{
    if (canExecuteMyButton)
    {
        canExecuteMyButton = false;
        CommandManager.InvalidateRequerySuggested();
        await _navigation.ShowMyButton();
        canExecuteMyButton = true;
        CommandManager.InvalidateRequerySuggested();
    }
}