如何在Windows窗体中使用MVVM显示WPF控件
我需要将WPF控件集成到现有的Windows Forms应用程序中.执行此操作的最简单的方法是创建一个ElementHost
控件并将其Child
属性设置为我的WPF视图.效果很好,显示了视图.
I have a requirement to integrate a WPF control into an existing Windows Forms app. The simple and easiest way to do this would be to create an ElementHost
control and set its Child
property to my WPF View. This works fine, the view displays.
但是,与视图进行交互有点麻烦,并且需要修改后面的视图代码中的字段和内容.更好的是,如果我可以实例化基础视图的视图模型并以MVVM方式与之交互,只要我更改其视图模型的属性,便可以显示并更新视图.
However, interacting with the view then is a bit cumbersome, and requires modifying the fields and things in the views code behind. What would be better is if I could instantiate the underlying view's view-model and interact with it in the MVVM way, having the view display and update whenever I change the properties of its view-model.
有人知道这样做的方法吗?
Does anyone know a way to do this?
使用设计器无法做到这一点,但是当您在代码中添加ElementHost的Child时,可以直接创建并分配ViewModel.当您在此ViewModel上提交更改时,它们将直接反映在WPF视图中.
You can not do that with the designer, but as you add the Child of your ElementHost in code you can directly create and assign the ViewModel. As you commit changes on this ViewModel they get directly reflected in the WPF View.
MyView view = new MyView();
MyViewModel model = new MyViewModel();
view.DataContext = model;
ElementHost.Child = view;
model.SomeBoundProperty = somethingElse;
//Magic update of the WPF view