views:

948

answers:

2

Is there a way to add a resource to a ResourceDictionary from code without giving it a resource key?

For instance, I have this resource in XAML:

<TreeView.Resources>
    <HierarchicalDataTemplate DataType="{x:Type xbap:FieldPropertyInfo}"
        ItemsSource="{Binding Path=Value.Values}">
            <TextBlock Text="{Binding Path=Name}" />
    <HierarchicalDataTemplate>
</TreeView.Resources>

I need to create this resource dynamically from code and add it to the TreeView ResourceDictionary. However, in XAML having no Key means that it's used, by default, for all FieldPropertyInfo types. Is there a way to add it to the resource in code without having a key or is there a way I can use a key and still have it used on all FieldPropertyInfo types?

Here's what I've done in C# so far:

HierarchicalDataTemplate fieldPropertyTemplate = new HierarchicalDataTemplate("FieldProperyInfo");

fieldPropertyTemplate.ItemsSource = new Binding("Value.Values");

this.Resources.Add(null, fieldPropertyTemplate);

Obviously, adding a resource to the ResourceDictionary the key null doesn't work.

A: 

Use the type that you want the template to apply to as the key:

this.Resources.Add(FieldPropertyInfo.GetType(), fieldPropertyTemplate);

As with your template above you provide a type. You have to either have to provide a name or a type.

Orion Adrian
Though this runs, the template isn't being used by the TreeView. Seems like something about the Resource key is preventing it from being used.
Bob
@Orion: So you saw my answer, and completely edited yours to copy mine? Really classy...
Bob King
+3  A: 

Use the type that you want the template to apply to as the key:

HierarchicalDataTemplate fieldPropertyTemplate = new 
    HierarchicalDataTemplate("FieldProperyInfo");

fieldPropertyTemplate.SetBinding(
   HierarchialDataTemplate.ItemSourceProperty, 
   new Binding("Value.Values");
this.Resources.Add(FieldPropertyInfo.GetType(), fieldPropertyTemplate);

The reason your code wasn't working was your weren't actually setting the binding. You need to call SetBinding, with the property you want the binding bound to.

Bob King