从ViewModel对象创建视图

时间:2014-08-28 04:17:37

标签: wpf view mvvmcross viewmodel

我看到MvvmCross touch支持使用MvxViewModelRequest从ViewModel对象创建视图。

但是在MvvmCross WPF中,我只能使用

MvxViewModelRequest创建视图
Mvx.Resolve<IMvxSimpleWpfViewLoader>().CreateView(viewmodelRequest)

但是,我找不到从ViewModel对象创建View的方法?是否支持MvvmCross for WPF?

2 个答案:

答案 0 :(得分:1)

此功能默认不包含在Wpf中 - 但您可以轻松添加它。

逻辑类似于https://github.com/MvvmCross/MvvmCross/blob/v3.1/Cirrious/Cirrious.MvvmCross.Wpf/Views/MvxWpfViewsContainer.cs中基于请求的代码 - 类似于:

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

如果您愿意,可以将其构建到自定义视图容器或自定义视图展示器中。

答案 1 :(得分:0)

假设你有

public partial class LoginViewController : MvxViewController<LoginViewModel>

,如果我想在某个地方使用视图,你可以做类似

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

,其中

this.presentedCurrentController it's

var NSViewController presentedCurrentController;

非常感谢@cheesebaron linkanother one