views:

33

answers:

1
+1  Q: 

WPF XAML resources

Hello,

I would like to place some WPF Data Templates in a loose file that I can reference where needed in my UserControl. I do not want the Data Templates to be application wide (use app.config), I only want it to be specific to my library. Is there a way to do this besides placing the Data Templates in UserControls and then loading the UserControls?

Thanks.

+1  A: 

Create a ResourceDictionary and put them in that. You can then load the ResourceDictionary and access the contained DataTemplates using indexer syntax:

DataTemplate myTemplate = (DataTemplate)rd["MyTemplate"];

The ResourceDictionary is a XAML file which you would compile into your library just as you would with a UserControl or Window. If you want to ship the templates as loose (uncompiled) XAML then you can still use a ResourceDictionary, but would need to use XamlReader to load it from the .xaml source file.

itowlson
ResourceDictionary does not seem to be available from a class library.
Taylor
Use the WPF User Control library template, and just delete UserControl1. Alternatively, if you already have a "normal" Class Library project and want to put your resources in that, do an Add > New Item > WPF > UserControl, then go into XAML view and change the `<UserControl>` tag to `<ResourceDictionary>` (and delete the Height and Width attributes and the default `<Grid>` content), and finally go into the code-behind and change the base class from UserControl to ResourceDictionary. Bit of a kludge but it'll get you there!
itowlson