【发布时间】:2021-02-18 02:16:09
【问题描述】:
快速单击按钮时如何避免多次调用同一事件。
下面是代码: 我创建了一个自定义委托命令,如下所示
- 查看模型
namespace TestProject.ViewModels
{
public class TestViewModel
{
public CustomDelegateCommand MenuButtonClickCommand { get; set; }
public TestViewModel()
{
MenuButtonClickCommand = new CustomDelegateCommand (async () => await ShowMenuAction());
}
private async Task ShowMenuAction()
{
//await some stuff
}
}
}
- CustomDelegateCommand.cs
public class CustomDelegateTimerCommand : DelegateCommand
{
public CustomDelegateTimerCommand(Action executeMethod, Func<bool> validateMethod, Action onBusy = default(Action)) : base(executeMethod)
{
BackgroundTaskWaitHandle = new EventWaitHandle(true, EventResetMode.ManualReset);
_validateMethod = validateMethod;
_onBusy = onBusy;
}
}
我面临的问题是,每当用户快速单击按钮时,菜单列表弹出窗口就会打开多次。 我的项目中有很多命令,我需要一个可以在全球范围内工作的解决方案。
我尝试使用 ObservesCanExecute() 解决如下问题,但我不喜欢为每个命令创建单独变量的想法,因为我的项目中有很多命令并且我不想要按钮当 CanExecute = false 时进入禁用状态。
- 视图模型
MenuButtonClickCommand = new CustomDelegateCommand (async () => await ShowMenuAction().ObservesCanExecute(() => CanExecute );
private async Task ShowMenuAction()
{
CanExecute = false;
//await some stuff
CanExecute = true;
}
非常感谢任何帮助!
【问题讨论】:
-
你可以绑定按钮的
IsEnabled,当用户点击它时设置为false,处理逻辑后设置为true。
标签: xamarin xamarin.forms mvvm command