gpt4 book ai didi

wpf - WPF 中的 ResourceDictionary 中没有键的 DataTemplate

转载 作者:行者123 更新时间:2023-12-03 03:47:46 25 4
gpt4 key购买 nike

我在 ResourceDictionary 中有几个 DataTemplate:

<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>

我在窗口中使用它:

<z:MyUserControl>
<z:MyUserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Dictionary.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</z:MyUserControl.Resources>
</z:MyUserControl>

数据模板和触发器工作正常。

我有两个问题:

  • 为什么 ResourceDictionary 中的 DataTemplate 不需要 x:Key?

  • 我可以用 Key 以某种方式将 ResourceDictionary 划分为多个部分,然后指向一个部分中的 DataTemplates 吗?

最佳答案

Why do DataTemplates in a ResourceDictionary not need a x:Key?

当您缺少 StyleDataTemplate 的键时,此结构:

<DataTemplate TargetType="{x:Type local:MyType}">

自动转换为:

<DataTemplate x:Key="{x:Type local:MyType}" TargetType="{x:Type local:MyType}">

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

Setting the TargetType property to the TextBlock type without setting an x:Key implicitly sets the x:Key to {x:Type TextBlock}. This also means that if you give the above Style an x:Key value of anything other than {x:Type TextBlock}, the Style would not be applied to all TextBlock elements automatically. Instead, you need to apply the style to the TextBlock elements explicitly.

<小时/>

When I give the DataTemplates a Key they stop to work

当你为DataTemplate指定一个key时,应该使用这个key,如:

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

<MainWindowViewModels:MainViewModel />
</ContentControl>
<小时/>

Can I divide the ResourceDictionary somehow in sections with a Key and then point to the DataTemplates in a section?

不幸的是,ResourceDictionary 是 Quote :

class is not derived from DictionaryBase. Instead, the ResourceDictionary class implements IDictionary but relies on a Hashtable internally.

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

关于wpf - WPF 中的 ResourceDictionary 中没有键的 DataTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22261756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com