2017-10-20 8 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> 

ビューのムーデル。ここで

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> 

ビューのムーデル。

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

私はドン関連性は分かりません。 –

関連する問題