如何在Windows窗体中使用MVVM显示WPF控件 [英] How do I use MVVM from within Windows Forms to display a WPF control

查看:269
本文介绍了如何在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

这篇关于如何在Windows窗体中使用MVVM显示WPF控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆