它没有,则需要使用第三方库,提供异步命令。我个人喜欢Nito.Mvvm.Async,它给你一个AsyncCommand,你可以使用并绑定你的函数。当异步函数运行时,该按钮将被禁用,并且一旦该功能完成,该按钮将重新启用。
<ContentPage.ToolbarItems>
<ToolbarItem Text = "Done" Command="{Binding DoneCommand}" />
<ToolbarItem Text = "Cancel" Command="{Binding CancelCommand}" Priority="1" />
</ContentPage.ToolbarItems>
在您的视图moodel。
public MyViewModel()
{
CancelCommand = new AsyncCommand(ExecuteCancel);
}
public AsyncCommand CancelCommand {get;}
async Task ExecuteCancel()
{
await Navigation.PopModalAsync();
}
这里是一个更复杂的版本,禁用取消选项,除非完成选项当前正在运行。
<ContentPage.ToolbarItems>
<ToolbarItem Text = "Done" Command="{Binding DoneCommand}" />
<ToolbarItem Text = "Cancel" Command="{Binding CancelCommand}" Priority="1" />
</ContentPage.ToolbarItems>
在您的视图moodel。
public MyViewModel()
{
DoneCommand = new AsyncCommand(ExecuteDone);
CancelCommand = new CustomAsyncCommand(ExecuteCancel, CanExecuteCancel);
PropertyChangedEventManager.AddHandler(DoneCommand, (sender, e) => CancelCommand.OnCanExecuteChanged(), nameof(DoneCommand.IsExecuting));
PropertyChangedEventManager.AddHandler(CancelCommand, (sender, e) => CancelCommand.OnCanExecuteChanged(), nameof(CancelCommand.IsExecuting));
}
private bool CanExecuteCancel()
{
return DoneCommand.IsExecuting && !CancelCommand.IsExecuting;
}
public AsyncCommand DoneCommand { get; }
public CustomAsyncCommand CancelCommand { get; }
async Task ExecuteDone()
{
await ... //Do stuff
}
async Task ExecuteCancel()
{
await Navigation.PopModalAsync();
}
那么,它被称为同步? –
这应该给你一些看法:https://stackoverflow.com/questions/37419572/if-async-await-doesnt-create-any-additional-threads-then-how-does-it-make-appl – Thowk
我不知道看不到相关性。 –