【问题标题】:WPF - Defining DataTemplate inside ResourceDictionary without a keyWPF - 在 ResourceDictionary 中定义 DataTemplate 没有键
【发布时间】:2011-02-27 20:01:35
【问题描述】:

我见过很多次这种形式的wpf代码示例:

<Window.Resources>
    <DataTemplate DataType="{x:Type SomeType}">
        <!-- Elements defining the DataTemplate-->
    </DataTemplate>
</Window.Resources>

我理解用法,但我不明白为什么这种语法可以:因为 ResourceDictionary 实现了 IDictionary,因此我们添加到 Resource 属性的每个元素都必须指定一个键。现在我知道使用 DictionaryKeyPropertyAttribute,一个类可以提供一个隐式键值 - 但对于 DataTemplate 类,提供的属性是“DataTemplateKey”。我知道这听起来有点琐碎,但这个问题的动机是知道如何使用其他类,即使我之前没有看到使用示例的特权(也许是第 3 方......)。有人吗?

【问题讨论】:

    标签: wpf xaml


    【解决方案1】:

    正如您在问题中提到的,没有x:Key 属性的条目使用DataTemplateKey(SomeType) 作为键。您只能为资源中的特定SomeType 指定一个此类实例。 DataTemplateKey 派生自 TemplateKey,而 TemplateKey 本身派生自 ResourceKey。当然,这样的 DataTemplate 资源定义可以针对多种类型出现,并且保持唯一,因为每种类型的 DataTemplateKey 都是唯一的。

    例如,考虑以下资源定义:

      <Window.Resources>
        <!-- Generic Button data template -->
        <DataTemplate DataType="{x:Type Button}">
          <!-- Elements defining the DataTemplate-->
        </DataTemplate>
        <!-- Generic TextBlock data template -->
        <DataTemplate DataType="{x:Type TextBlock}">
          <!-- Elements defining the DataTemplate-->
        </DataTemplate>
        <!-- Specific Button data template -->
        <DataTemplate x:Key="SpecialButton" DataType="{x:Type Button}">
          <!-- Elements defining the DataTemplate-->
        </DataTemplate>
      </Window.Resources>
    

    这会在资源字典中产生三个条目。下图中的橙色箭头指向ButtonTextBlock 类型的基于DataTemplateKey 的条目,而红色箭头指向SpecialButton 键控资源的特定(键控)条目:

    【讨论】:

    • Michael:感谢您的详细回答,虽然我仍然有一个问题 - 我不明白 DataType 属性(对象类型)与您提到的 DataTemplateKey 类型有何关系。我认为我的困惑是基于这样一个事实,即对象类型的“DataTemplateKey”类型和“DataTemplateKey”属性名称...正如我从文档中了解到的那样,包装 DataTemplate 类的 DictionaryKeyPropertyAttribute 与“DataTemplateKey”有关属性,它是对象类型。你能否澄清这一点?再次感谢。
    猜你喜欢
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 2012-10-26
    • 1970-01-01
    相关资源
    最近更新 更多