2017-10-20 43 views
-1

如果我有这个...工具栏按钮如何知道要等待?

<ContentPage.ToolbarItems> 
    <ToolbarItem Text = "Done" Clicked="Done_Clicked" /> 
    <ToolbarItem Text = "Cancel" Clicked="Cancel_Clicked" Priority="1" /> 
</ContentPage.ToolbarItems> 

在后面的代码...

async void Cancel_Clicked(object sender, EventArgs e) 
{ 
    await Navigation.PopModalAsync(); 
} 

怎样工具栏项目知道它的处理器是异步的?

回答

1

它没有,则需要使用第三方库,提供异步命令。我个人喜欢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(); 
    } 
2

Cancel_Clicked处理程序返回void因此您的工具栏项(UI线程)无法知道您的方法是否异步。

编辑:
内蒙古方法PopModalAsync()将运行异步 - 它会在未来一段时间内完成工作。 Cancel_Clicked()将立即返回,对于UI线程它是同步操作。

+0

那么,它被称为同步? –

+1

这应该给你一些看法:https://stackoverflow.com/questions/37419572/if-async-await-doesnt-create-any-additional-threads-then-how-does-it-make-appl – Thowk

+0

我不知道看不到相关性。 –