Gintama
Gintama

Reputation: 1152

Create View from ViewModel object

I see that MvvmCross touch supports creating a View from a ViewModel object using a MvxViewModelRequest.

But in MvvmCross WPF, I can only create Views from a MvxViewModelRequest using

Mvx.Resolve<IMvxSimpleWpfViewLoader>().CreateView(viewmodelRequest)

However, I cannot find a way to create a View from a ViewModel object? Is this support in MvvmCross for WPF?

Upvotes: 0

Views: 850

Answers (2)

hbk
hbk

Reputation: 11184

Assume u have

public partial class LoginViewController : MvxViewController<LoginViewModel>

than, if i want to use view somewhere u can do something like

this.presentedCurrentController = Activator.CreateInstance(typeof(LoginViewController)) as LoginViewController;
(this.presentedCurrentController as LoginViewController).ViewModel = new LoginViewModel();

where

this.presentedCurrentController it's

var NSViewController presentedCurrentController;

Thanks too @cheesebaron for link and another one

Upvotes: 0

Stuart
Stuart

Reputation: 66882

This functionality isn't included by default in Wpf - but you could easily add it.

The logic would be similar to the request-based code in https://github.com/MvvmCross/MvvmCross/blob/v3.1/Cirrious/Cirrious.MvvmCross.Wpf/Views/MvxWpfViewsContainer.cs - something like:

  // Use `IMvxViewFinder` to find the type of view: 
  var viewType = Mvx.Resolve<IMvxViewFinder>().GetViewType(myViewModel.GetType());

  // create a view and set the data context
  var viewObject = Activator.CreateInstance(viewType);
  if (viewObject == null)
     throw new MvxException("View not loaded for " + viewType);

  var wpfView = viewObject as IMvxWpfView;
  if (wpfView == null)
     throw new MvxException("Loaded View does not have IMvxWpfView interface " + viewType);

  wpfView.ViewModel = myViewModel;

You could build this into a custom views container or a custom view presenter if you wanted to.

Upvotes: 1

Related Questions