【问题标题】:How to load DataTemplate from another Assembly如何从另一个程序集加载 DataTemplate
【发布时间】:2014-08-08 15:29:15
【问题描述】:

情况如下: 程序集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();

【问题讨论】:

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


    【解决方案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 引用。

    【讨论】:

    • 我不想更改 App.xaml,因为我不想重新编译我的 .EXE 文件。我只是想修改AnotherAssembly项目。
    • 好的,我给的链接告诉你怎么做:Application.Current.Resources.MergedDictionaries.Add(resource);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    • 2012-02-15
    • 2011-05-06
    • 2015-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多