P10trek P10trek - 1 month ago 22
C# Question

Run async method from Xaml

How Can i run async method from Xaml(on Click), normally i using something like this:

xmlns:ii="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:eii="http://schemas.microsoft.com/expression/2010/interactions"

<Button Height="30" Width="200" Content="Save" >
<ii:Interaction.Triggers>
<ii:EventTrigger EventName="Click">
<eii:CallMethodAction TargetObject="{Binding}" MethodName="Saveing"/>
</ii:EventTrigger>
</ii:Interaction.Triggers>
</Button>


Saveing method:

public async Task Saveing(){...}

Answer

The whole point of MVVM is to separate the UI from the processing.

Bind the Command property of your button, to a ICommand (RelayCommand or other implementation) item in your ViewModel. The associated method for this command can be called in an async manner e.g.

public ICommand SaveCommand {get; private set;}

private async Task SaveMethodAsync() 
{
    await dbService.SaveDataAsync(modelItem).ConfigureAwait(false);
    ...
}


pubic ViewModel()
{
    SaveCommand = new RelayCommand(async () => await SaveMethodAsync().ConfigureAwait(false));
}