Krekkon
Krekkon

Reputation: 1347

How pass parameter and async keyword in lambda method?

How can I pass the framworkElement and use an async keyword too in this code?

SaveImage = new RelayCommand<FrameworkElement>(frameworkElementForPrint =>  
{
    StorageFile file = await PickImageFileToSave();
    SaveVisualElementToFile(frameworkElementForPrint, file);
});

Becaue now the await can not be used...

Upvotes: 2

Views: 2411

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 457402

I recommend that you factor all your logic into a separate method, as such:

public async Task SaveImageAsync(FrameworkElement frameworkElementForPrint)
{
  StorageFile file = await PickImageFileToSaveAsync();
  await SaveVisualElementToFileAsync(frameworkElementForPrint, file);
}

Then wrap this into the RelayCommand:

SaveImage = new RelayCommand<FrameworkElement>(async arg => { await SaveImageAsync(arg); });

This separation allows you to unit test your SaveImageAsync logic (assuming of course that you refactor with proper abstractions).

This MSDN article has a little more detail on async commands.

Upvotes: 6

Related Questions