amnezjak
amnezjak

Reputation: 2031

How to load DataTemplate from another Assembly

Here's the situation: Assembly Common implements CommonMessageBox.xaml window with ContentControl bound to its DataContext. Assembly AnotherAssembly implements MyViewModel class and a ResourceDictionary with some DataTemplate for the MyViewModel. It also references the Common assembly. I want to showCommonMessageBox window and assign object of MyViewModel type to its DataContext.

The question is: (How) can I (elegantly and preferrably in XAML) inject ResourceDictionary from AnotherAssembly to CommonMessageBox window's resources without changing the Common assembly or App.xaml?

This solution works, but I was wondering if there is another/simpler/more elegant way?

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();

Upvotes: 1

Views: 766

Answers (1)

Muster Station
Muster Station

Reputation: 514

In App.xaml

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

In CommonMessageBox.xaml you can also set your DataContext like this

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

Now you can change those App.xaml references using code I posted here.

Upvotes: 1

Related Questions