vargonian
vargonian

Reputation: 3234

DataTemplate created using XamlReader.Parse does not have its DataTemplateKey property set - why not?

Let's say I have a simple DataTemplate declaration; it doesn't even need content:

<DataTemplate x:Key="myListBoxItemTemplate" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" />

..which is generated from the following C# code:

    private string GenerateDataTemplateXaml()
    {
        const string xamlNamespaceString = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
        const string xamlXNamespaceString = "http://schemas.microsoft.com/winfx/2006/xaml";
        XNamespace defaultNamespace = xamlNamespaceString;
        XNamespace x = xamlXNamespaceString;

        XElement dataTemplate =
            new XElement(defaultNamespace + "DataTemplate",
                new XAttribute(x + "Key", "myListBoxItemTemplate"),
                new XAttribute(XNamespace.Xmlns + "x", xamlXNamespaceString),
                new XAttribute("xmlns", xamlNamespaceString));                   

        return dataTemplate.ToString();
    }

I want to load this into my MainWindow's Resources using XamlReader.Parse on the generated XAML string.

    public MainWindow()
    {
        InitializeComponent();

        string dataTemplateText = this.GenerateDataTemplateXaml();
        DataTemplate dataTemplate = (DataTemplate)XamlReader.Parse(dataTemplateText);
    }

This runs without exception, but the resulting DataTemplate doesn't have its DataTemplateKey property set (it's null). I would expect this to have a value of "myListBoxItemTemplate". So, if I want to add this template to the MainWindow's resources, I need to refer to the key again explicitly (which seems redundant):

this.Resources.Add("myListBoxItemTemplate", dataTemplate);

Why is dataTemplate.DataTemplateKey null after loading valid XAML which defines this key?

(I've got bigger issues I'm encountering but this may clue me in as to why those are happening as well.)

Upvotes: 1

Views: 186

Answers (1)

Clemens
Clemens

Reputation: 128023

Setting x:Key does not set the DataTemplate's DataTemplateKey property.

It is the other way round. See the Remarks:

If you do not set the x:Key Directive on a DataTemplate that is in a ResourceDictionary, the DataTemplateKey is used as the key.

Upvotes: 1

Related Questions