2016-01-20 174 views
0

下面的代碼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)'"

+0

對於相同類型('IssueType'),您有2個'DataTemplate'。刪除一個,最有可能的是後者 – dkozl

回答

0

當你把東西放到一個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進行引用。