Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a XAML Resource from Code Without a Key

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.

like image 395
Bob Wintemberg Avatar asked Sep 26 '08 18:09

Bob Wintemberg


People also ask

How to create resource dictionary?

Tip You can create a resource dictionary file in Microsoft Visual Studio by using the Add > New Item… > Resource Dictionary option from the Project menu.

What is ResourceDictionary?

A resource dictionary is a repository for XAML resources, such as styles, that your app uses. You define the resources in XAML and can then retrieve them in XAML using the {StaticResource} markup extension and {ThemeResource} markup extension s. You can also access resources with code, but that is less common.

What is code behind XAML?

Code-behind is a term used to describe the code that is joined with markup-defined objects, when a XAML page is markup-compiled. This topic describes requirements for code-behind as well as an alternative inline code mechanism for code in XAML.


1 Answers

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.

like image 53
Bob King Avatar answered Nov 14 '22 21:11

Bob King