如何从另一个程序集加载DataTemplate

时间:2014-08-08 15:29:15

标签: c# wpf xaml .net-4.0 resourcedictionary

以下是这种情况:  程序集Common实现CommonMessageBox.xaml窗口,ContentControl绑定到DataContext。大会AnotherAssembly实施MyViewModel课程,ResourceDictionary实施DataTemplate MyViewModel。它还引用了Common程序集。我想显示CommonMessageBox窗口并将MyViewModel类型的对象分配给其DataContext

问题是:(如何)我(在XAML中优雅且优先)注入 ResourceDictionaryAnotherAssemblyCommonMessageBox窗口的资源没有更改Common程序集或App.xaml

这个解决方案有效,但我想知道是否还有其他/更简单/更优雅的方式?

CommonMessageBox w = new CommonMessageBox();
w.DataContext = new MyViewModel();
w.Resources.MergedDictionaries.Add(new ResourceDictionary() { Source = new Uri(@"/AnotherAssembly;component/DataTemplateDictionary.xaml", UriKind.RelativeOrAbsolute) });
w.ShowDialog();

1 个答案:

答案 0 :(得分:1)

在App.xaml中

<Application.Resources>
   <ResourceDictionary>
      <ResourceDictionary.MergedDictionaries>
         <ResourceDictionary Source = "/AnotherAssembly;component/DataTemplateDictionary.xaml" />
      </ResourceDictionary.MergedDictionaries>
   </ResourceDictionary>
</Application.Resources>

在CommonMessageBox.xaml中,您还可以像这样设置DataContext

<UserControl xmlns:viewmodels="clr-namespace:AnotherAssemblyNamespace;assembly=AnotherAssembly">
   <UserControl.DataContext>
      <viewmodels:MyViewModel />
   </UserControl.DataContext>
</UserControl>

现在,您可以使用我发布的代码here更改这些App.xaml引用。