Search code examples
wpfviewmvvmcrossviewmodel

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?


Solution

  • 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.