使用 MEF 导入 WPF DataTemplate?
我一直将 MEF 视为一个可扩展性框架,除了一点之外,我几乎被说服了:
假设我想导入一个 ViewModel 和一个 View 来显示它。 我认为“正确”的方法是让 MEF 部分导出 ViewModel 类和显示 ViewModel 的 DataTemplate。 举个例子,假设您正在构建一个类似 Visio 的应用程序,并且想要导入形状库。 每个形状都需要一个在 Xaml 中定义的视图和一个包装某些底层模型对象的 ViewModel。
这可能吗? DataTemplate 的导入协定是什么样的?如何让 WPF 了解导入的 DataTemplate?
I was looking at MEF as an extensibility framework, and I'm pretty much sold, except for one point:
Let's say I want to import both a ViewModel and a View to display it. I think the "right" way to do that is for the MEF part to export a ViewModel class, and a DataTemplate that displays the ViewModel. As an example, say you were building a Visio-like application and you want to import a library of shapes. Each shape needs a View defined in Xaml and a ViewModel that would wrap some underlying Model object.
Is this possible? What would the Import contract look like for the DataTemplate and how do I make WPF aware of the imported DataTemplate?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,我能够通过以下方式完成这项工作:
在我的主机 WPF 应用程序中,我添加了此导入:
然后在我的复合部分中,我在常规 ResourceDictionary Xaml 文件中声明了一个 ViewModel 以及该 ViewModel 的数据模板。 然后,我为 ResourceDictionary 创建了一个隐藏代码,如下所示(在本示例中,ViewModel 称为 ItemViewModel,ResourceDictionary 称为 ItemView):
作为参考,示例 ResourceDictionary 的 Xaml 如下所示:
然后,回到我的主机 WPF 中在我成功编写应用程序之后、显示主窗口之前,我执行以下操作:
这似乎成功地将 DataTemplate 应用到 WPF 看到 ItemViewModel 的任何位置。
编辑:对于任何感兴趣的人,我发布了一个名为 SoapBox Core 的开源应用程序框架,它广泛使用这种方法将视图导入到应用程序资源中。 它运行得很好,你可以自己下载源码并看看它是如何运行的。
Yes, I was able to make this work in the following way:
In my host WPF application, I added this Import:
Then in my composite part, I declared a ViewModel, and a data template for the ViewModel in a regular ResourceDictionary Xaml file. Then I created a code behind for the ResourceDictionary, like this (in this example, the ViewModel is called ItemViewModel and the ResourceDictionary is called ItemView):
For reference, the Xaml for the example ResourceDictionary looks like this:
Then, back in my host WPF application, after I successfully compose and before I show the main window, I do this:
That seems to successfully apply the DataTemplate anywhere WPF sees an ItemViewModel.
EDIT: For anyone who's interested, I released an application framework called SoapBox Core as open source, and it uses this method extensively to import Views into the application resources. It works very well, and you can download the source yourself and take a look at how it works.