以下是这种情况:
程序集Common
实现CommonMessageBox.xaml
窗口,ContentControl
绑定到DataContext
。大会AnotherAssembly
实施MyViewModel
课程,ResourceDictionary
实施DataTemplate
MyViewModel
。它还引用了Common
程序集。我想显示CommonMessageBox
窗口并将MyViewModel
类型的对象分配给其DataContext
。
问题是:(如何)我(在XAML中优雅且优先)注入 ResourceDictionary
从AnotherAssembly
到CommonMessageBox
窗口的资源没有更改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();
答案 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引用。