在WPF中的ResourceDictionary中没有键的DataTemplate

Ger*_*ard 9 wpf xaml resourcedictionary

我有几个DataTemplates ResourceDictionary:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:z="clr-namespace:ZoomPan">
    <DataTemplate DataType="{x:Type z:Circle}">
        <z:Circle Center="{Binding Center}" Radius="{Binding Radius}" x:Name="circle"/>
        <DataTemplate.Triggers>
            <DataTrigger ... />
        </DataTemplate.Triggers>
    </DataTemplate>
    .... etc.
</ResourceDictionary>
Run Code Online (Sandbox Code Playgroud)

我用它来Window:

<z:MyUserControl>
    <z:MyUserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Dictionary.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </z:MyUserControl.Resources>
</z:MyUserControl>
Run Code Online (Sandbox Code Playgroud)

DataTemplates和触发器工作正常.

我有两个问题:

  • 为什么ResourceDictionary中的DataTemplates不需要ax:Key?

  • 我可以在某个部分用一个Key划分ResourceDictionary,然后指向一个部分中的DataTemplates吗?

Ana*_*aev 10

为什么ResourceDictionary中的DataTemplates不需要ax:Key?

当你错过了Style或者DataTemplate这个结构的关键时:

<DataTemplate TargetType="{x:Type local:MyType}">
Run Code Online (Sandbox Code Playgroud)

自动转换为:

<DataTemplate x:Key="{x:Type local:MyType}" TargetType="{x:Type local:MyType}">
Run Code Online (Sandbox Code Playgroud)

这意味着Style/DataTemplate将显式用于此类型的所有控件,因为在ResourceDictionaries不能没有键的元素中,这样做是为了简化结构.引用自MSDN:

将TargetType属性设置为TextBlock类型而不设置x:Key implicitly sets the x:Key to {x:Type TextBlock}.这也意味着如果为上面的Style赋予x:Key值除{x:Type TextBlock}以外的任何值,则Style不会应用于所有TextBlock元素自动.相反,您需要显式地将样式应用于TextBlock元素.


当我给DataTemplates一个密钥他们停止工作

指定密钥时DataTemplate,应将其用于此密钥,例如:

<ContentControl Name="MyContent"
                ContentTemplate="{StaticResource MainView}"> // here set the key

    <MainWindowViewModels:MainViewModel />
</ContentControl>
Run Code Online (Sandbox Code Playgroud)

我可以在某个部分用一个Key划分ResourceDictionary,然后指向一个部分中的DataTemplates吗?

不幸的是,ResourceDictionary是Quote:

class不是源于DictionaryBase.相反,ResourceDictionary类实现IDictionary 但在内部依赖于Hashtable.

在这种情况下,它不是有序字典,其中每个元素都分配给散列.用于分离使用的词典区域ResourceDictionary.MergedDictionaries.