为什么ResourceDictionary中的ControlTemplate需要x:key

luk*_*san 8 wpf xaml resourcedictionary controltemplate

考虑以下XAML文件:

<Window x:Class="ExpressionVisualizer.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sle="clr-namespace:System.Linq.Expressions;assembly=System.Core"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <DataTemplate DataType="{x:Type sle:BinaryExpression}"/>
        <ControlTemplate TargetType="{x:Type ContentControl}"/>
    </Window.Resources>
</Window>
Run Code Online (Sandbox Code Playgroud)

这给出了以下编译错误:

添加到IDictionary的所有对象必须具有Key属性或与其关联的其他类型的键.第10行位置10.

如果我x:key向ControlTemplate 添加一个属性,它会编译.但是,我不应该这样做.ControlTemplate使用DictionaryKeyProperty属性进行修饰,该属性将TargetType指定为键属性.因此,只要我为ControlTemplate指定TargetType,不必指定显式键(类似于我没有在我定义的DataTemplate上指定一个键).

我有第二个与切向相关的问题.如果我在XAML中以这种方式定义ControlTemplate(或者是否指定键),它是否会自动应用于未指定其他模板的ContentControl类型的所有控件,或者我是否必须将ControlTemplate嵌入到样式中要发生这种情况?

nem*_*esv 5

从MSDN ControlTemplate

如果您在资源部分中拥有一个独立的ControlTemplate,并且TargetType属性设置为一种类型,则ControlTemplate不会自动应用于该类型。相反,您需要指定x:Key并显式应用模板。

另请注意,如果模板
定义包含ContentPresenter,则ControlTemplate上需要TargetType属性。

因此,ControlTemplate不会自动应用,您必须始终指定x:Key。因此,DictionaryKeyProperty这并不适用。

我做了一些研究:

尽管DictionaryKeyPropertyAttribute MSDN页面指出:

WPF使用说明

以下列表引用了应用了此属性的WPF API的示例:

ControlTemplate.TargetType

DataTemplate.DataTemplateKey

Style.TargetType
Run Code Online (Sandbox Code Playgroud)

但是在“ 资源概述”页面上,他们仅提及Styles, DataTemplates, and Implicit Keys其中具有隐式键。这也意味着您尽管需要使用,也必须始终指定x:Keyfor 。ControlTemplateDictionaryKeyProperty

顺便说一句,DictionaryKeyPropertyAttirubte看此连接问题似乎有些问题