TreeView的多层次
问题描述:
下面的代码TreeView的多层次
<TreeView Name="tree" ItemsSource="{Binding Path=AllNotes}">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type m:Note}" ItemsSource="{Binding Path=ListIssuesType}">
<TextBlock Text="{Binding Path=SoftwareVersion}" Margin="2" />
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type m:IssueType}" ItemsSource="{Binding Path=IssueNames}">
<TextBlock Text="{Binding Path=IssueTypeName}" Margin="2" />
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type m:IssueType}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=IssueTypeName}" />
</StackPanel>
</DataTemplate>
</TreeView.Resources>
</TreeView>
我得到的错误:
"Item has already been added. Key in dictionary: 'DataTemplateKey(ReleaseNotes_Window.Models.IssueType)' Key being added: 'DataTemplateKey(ReleaseNotes_Window.Models.IssueType)'"
答
当你把东西放到一个ResourceDictionary
,要么需要一个明确的x:Key
或键将被确定该类应用DictionaryKeyPropertyAttribute
。
对于DataTemplate
它是这样的:
[DictionaryKeyProperty("DataTemplateKey")]
public class DataTemplate : FrameworkTemplate
这将取决于DataType
。
因为你有:
<HierarchicalDataTemplate DataType="{x:Type m:IssueType}" ItemsSource="{Binding Path=IssueNames}">
<TextBlock Text="{Binding Path=IssueTypeName}" Margin="2" />
</HierarchicalDataTemplate>
而且
<DataTemplate DataType="{x:Type m:IssueType}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=IssueTypeName}" />
</StackPanel>
</DataTemplate>
都与DataType="{x:Type m:IssueType}"
,这就是为什么程序失败。
对DataTemplate
之一使用额外的x:Key
,并将其作为您计划使用它的StaticResource
进行引用。
对于相同类型('IssueType'),您有2个'DataTemplate'。删除一个,最有可能的是后者 – dkozl