Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use MVVM from within Windows Forms to display a WPF control

Tags:

winforms

mvvm

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.

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?

like image 252
cjroebuck Avatar asked Nov 14 '22 01:11

cjroebuck


1 Answers

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
like image 133
fixagon Avatar answered Dec 22 '22 07:12

fixagon