2

I'm creating a modal window, assigning it's DataContext to my view model, then calling ShowDialog.

var vm = new MyViewModel();  // implements INotifyPropertyChanged

// populate vm properties here

var window = new MyWindow(); // inherits from System.Windows.Window
window.DataContext = vm;
window.ShowDialog();

However, I want to populate properties of the viewmodel from the results of an async method.

vm.Result = await provider.GetResultAsync();

and I want those changes to be visible to data-bound properties in the window.

I can't do this before the call to ShowDialog, because then ShowDialog will only be called after the result is available.

I can't do this after the call to ShowDialog, because ShowDialog blocks until the window is closed.

How can I do this?

4 Answers 4

2

move this code inside MyWindow Class

then in window_loaded()

var vm = new MyViewModel();  // implements INotifyPropertyChanged

// populate vm properties here

this.DataContext = vm;
5
  • 1) Can this be done using await-ed results? 2) I can attach to the Loaded event outside of MyWindow. This is important, because in my case MyWindow is defined in a different DLL, and I can't really change it.
    – Zev Spitz
    May 19, 2020 at 18:12
  • I think await / async depend on the provider .
    – Wowo Ot
    May 19, 2020 at 18:19
  • For the purpose of the question, you can safely assume provider has an async method called GetResultAsync which returns a Task-ed value.
    – Zev Spitz
    May 19, 2020 at 18:21
  • No, it does not.
    – Zev Spitz
    May 19, 2020 at 18:38
  • sorry I couldn't help !
    – Wowo Ot
    May 19, 2020 at 22:52
1

You can do it in many ways. I recommend the @WowoOt's answer since the view model must be part of your window in which you are trying to be using.

Another way of accomplishing it, is to use the Task.ContinueWith method in the call of provider.GetResultAsync(), and then write the assigment vm.Result = task.Response in the callback. However, this only works if your view model implements INotifyPropertyChanged.

Here is the code for this:

private void ButtonBase_OnClick(object sender, RoutedEventArgs e) {
    // Supposed to open the window after clicking a button.
    var vm = new MyViewModel();
    var window = new MyWindow {
        DataContext = vm
    };
    //vm.Result = await GetResultAsync();
    _ = GetResultAsync().ContinueWith(x => vm.Result = x.Result);

    window.ShowDialog();

    static async Task<string> GetResultAsync() {
        await Task.Delay(1000); // just to simulate a long process to recover the data.
        return $"generated string: {new Random().Next(10)}";
    }
}

My sample view model implements the INotifyPropertyChanged interface, to notify the XAML framework about any changes in its properties.

public class MyViewModel : INotifyPropertyChanged {
    private string result;
    public string Result {
        get => this.result;
        set {
            this.result = value;
            this.OnPropertyChanged();
        }
    }

    #region INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    } 
    #endregion
}
2
  • 1) The viewmodel implements INotifyPropertyChanged, as noted in the question. 2) Why do I need to introduce a new local function? _ = provider.GetResultAsync().ContinueWith(x => vm.Result = x.Result); should work just as well. 3) the view model must be part of the window in which you are trying to use it Not really. The same window could use different view model types, and the same viewmodel type could be applied to multiple views. 4) Why do I need to assign to a discard (_)?
    – Zev Spitz
    May 19, 2020 at 18:37
  • @ZevSpitz in the code, the local function is to give a complete solution, you need to replace it with your provider's method. The intend to use a view model is to shape the elements in your UIElement (Window, UserControl, etc.), so you don't need to write multiples view models for a view. May 19, 2020 at 18:41
0

Thanks to @Wowo Ot's answer and @Marlonchonsky's answer, I am doing the following:

var vm = new MyViewModel();
var window = new MyWindow();
window.DataContext = vm;
window.Loaded += async (s, e) => vm.Result = await provider.GetResultAsync();
window.ShowDialog();

and it works.

-1

You can do something like this

vm.GetResultsTask = provider.GetResultsAsync();

Then when you need the results in the MyWindow you will do await DataContext.GetResultsTask to get them.

2
  • I don't have code that explicitly gets the results; I am relying on databinding. When should I write await DataContext.GetResultsTask;?
    – Zev Spitz
    May 19, 2020 at 18:10
  • I would suggest incorporating this information in your answer. Assuming this works, I prefer it, because it could encapsulate the result retrieval in the view model.
    – Zev Spitz
    May 19, 2020 at 18:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.