How do I use MVVM from within Windows Forms to dis

2019-02-22 08:21发布

问题:

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.

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?

回答1:

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


回答2:

The essence of MVVM is binding. Since you do not have that in Windows Forms, I am afraid you cannot use MVVM in there.