这是您可以使用的技巧。
- 确保您的 Silverlight 视图和视图模型在它们自己的程序集中被隔离,您的 WPF 应用程序可以轻松引用这些程序集。
- 添加对 Silverlight 类库的引用,该类库包含 WPF 应用程序中的视图和视图模型。
将 UserControl 的内容“CustomerView”移动到位于名为“customerViewTemplate”的资源字典中的 DataTemplate
在 Silverlight 和 WPF 中的根 UI 元素 XAML 文件中执行以下操作:
<ContentControl ContentTemplate="{Staticresource customerViewTemplate}" />
- 在 Silverlight 应用程序的 App.xaml 中,确保将以下资源字典引用添加到合并字典。
<ResourceDictionary Source="MyApp.Views;component/CustomerViewResources.xaml" />
- 在 WPF 应用程序的 App.xaml 中,确保将以下资源字典引用添加到合并字典中。
<ResourceDictionary Source="pack://application:,,,/MyApp.Views;component/CustomerViewResources.xaml" />
对不起编号,看起来 Stack Overflow 的有序列表机制有点不对劲。
之所以可行,是因为您不能直接从 WPF 中的 XAML 引用 Silverlight UserControl。它会给你以下错误:
'无法解析对程序集 'System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' 的依赖,因为它没有被预加载。使用 ReflectionOnly API 时,必须通过 ReflectionOnlyAssemblyResolve 事件预加载或按需加载依赖程序集。
如果您尝试使用 C# 将 UserControl 强制到 WPF Grid 上,您将收到以下 3 个错误:
'System.Windows.Controls.UIElementCollection.Add(System.Windows.UIElement)' 的最佳重载方法匹配有一些无效参数。
'System.Windows.Controls.UserControl' 类型在未引用的程序集中定义。您必须添加对程序集 'System.Windows, Version=2.0.5.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e' 的引用
无法从“ToWpfTest.Views.TestView”转换为“System.Windows.UIElement”
我认为这是因为 WPF 中的 System.Windows.UIElement 与 Silverlight 中的 System.Windows.UIElement 不同。