使用 XamlReader.Parse 创建的 DataTemplate 没有设置其 DataTemplateKey 属性 - 为什么不呢?

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

假设我有一个简单的 DataTemplate 声明;它甚至不需要内容:

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

..由以下 C# 代码生成:

    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();
    }

我想在生成的 XAML 字符串上使用 XamlReader.Parse 将它加载到我的主窗口的资源中。

    public MainWindow()
    {
        InitializeComponent();

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

这会无一例外地运行,但生成的 DataTemplate 没有设置其 DataTemplateKey 属性(它为空)。我希望它的值为 "myListBoxItemTemplate"。所以,如果我想把这个模板添加到 MainWindow 的资源中,我需要再次明确地引用该键(这似乎是多余的):

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

为什么加载后 dataTemplate.DataTemplateKey 为 null 定义此键的有效 XAML?

(我遇到了更大的问题,但这可能会让我明白为什么会发生这些问题。)

设置 x:Key 不会设置 DataTemplate 的 DataTemplateKey 属性.

正好相反。见 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.