views:

498

answers:

1

I'm trying to figure out how to add a DataTemplate to the app's resource dictionary. I'm familiar with how to do so when the DataTemplate is in XAML (via a uri), but I'm kind fuzzy at how to do so when the DataTemplate is defined in code.

What I have, which isn't working is-

        //Create DataTemplate
        DataTemplate template = new DataTemplate(typeof(CoordinateViewModel));
        FrameworkElementFactory ViewStack = new FrameworkElementFactory(typeof(CoordinateView));
        ViewStack.Name = "myViewStack";

        template.VisualTree = ViewStack;


        ResourceDictionary dictionary = new ResourceDictionary();
        dictionary.BeginInit();
        dictionary.Add(template, template);
        dictionary.EndInit();

        App.Current.Resources.MergedDictionaries.Add(dictionary);

EDIT: As best as I can the DataTemplate doesn't make it into the App's resource dictionary, despite not throwing any errors. When the ViewModel is later called from XAML, it acts as though there is not a proper DataTemplate to display it. For example,

<StackPanel>
    <ContentPresenter Content="{Binding ViewModel}" />
</StackPanel>

Results in an empty window with the text "ShellPrototype.ViewModels.CoordinateViewModel" displayed- EG, it doesn't have a template to display the view.

+1  A: 

The key here, in order to make this work correctly, is to use DataTemplateKey:

ResourceDictionary dictionary = new ResourceDictionary();
dictionary.Add(new DataTemplateKey(typeof(CoordinateViewModel)), template);

If you do this, it should work as specified. However, the FrameworkElementFactory is, according to the docs, "a deprecated way to programmatically create templates", so you may want to parse the XAML directly.

Reed Copsey