P10trek P10trek - 5 months ago 55
C# Question

Run async method from Xaml

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


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

Saveing method:

public async Task Saveing(){...}


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));