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.
我需要将WPF控件集成到现有的Windows窗体应用程序中。最简单和最简单的方法是创建一个ElementHost控件并将其Child属性设置为我的WPF视图。这样工作正常,视图显示。
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.
但是,与视图交互有点麻烦,并且需要修改后面的视图代码中的字段和事物。更好的是,如果我可以实例化底层视图的视图模型并以MVVM方式与其交互,只要我更改其视图模型的属性,就可以显示和更新视图。
Does anyone know a way to do this?
有谁知道这样做的方法?
2 个解决方案
#1
4
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.
您无法使用设计器执行此操作,但在代码中添加ElementHost的Child时,您可以直接创建并分配ViewModel。当您在此ViewModel上提交更改时,它们会直接反映在WPF视图中。
MyView view = new MyView();
MyViewModel model = new MyViewModel();
view.DataContext = model;
ElementHost.Child = view;
model.SomeBoundProperty = somethingElse;
//Magic update of the WPF view
#2
-5
The essence of MVVM is binding. Since you do not have that in Windows Forms, I am afraid you cannot use MVVM in there.
MVVM的本质是绑定。由于您在Windows窗体中没有,我担心您不能在那里使用MVVM。
#1
4
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.
您无法使用设计器执行此操作,但在代码中添加ElementHost的Child时,您可以直接创建并分配ViewModel。当您在此ViewModel上提交更改时,它们会直接反映在WPF视图中。
MyView view = new MyView();
MyViewModel model = new MyViewModel();
view.DataContext = model;
ElementHost.Child = view;
model.SomeBoundProperty = somethingElse;
//Magic update of the WPF view
#2
-5
The essence of MVVM is binding. Since you do not have that in Windows Forms, I am afraid you cannot use MVVM in there.
MVVM的本质是绑定。由于您在Windows窗体中没有,我担心您不能在那里使用MVVM。