Home > OS >  WPF: The key is already defined in this scope
WPF: The key is already defined in this scope

Time:06-12

I'm working with TreeView and I want two ObservableCollections (KategorijeLekovi and KategorijeRadnici) to be shown under a node (which is an object of class Apoteka). I get this error: "The key is already defined in this scope." and it reffers to the second DataType="{x:Type local:Apoteka}". However, if I delete this DataType, I get a different error: "All objects added to an IDictionary must have a Key attribute or some other type of key associated with them."

<TreeView Grid.Column="0" Grid.Row="0" Name="trv1" >
                <TreeView.Resources>
                    <HierarchicalDataTemplate DataType="{x:Type local:Apoteka}" ItemsSource="{Binding KategorijeLekovi}">
                        <StackPanel Orientation="Horizontal">
                            <TextBlock  Text="{Binding Naziv}"/>
                        </StackPanel>
                    </HierarchicalDataTemplate>

                    <HierarchicalDataTemplate DataType="{x:Type local:Apoteka}" ItemsSource="{Binding KategorijeRadnici}">
                        <StackPanel Orientation="Horizontal">
                            <TextBlock  Text="{Binding Naziv}"/>
                        </StackPanel>
                    </HierarchicalDataTemplate>
...

CodePudding user response:

Thank you all for answering, I managed to solve it with your help. Instead of having two ObservableCollections I made one, which had items from both KategorijeLekovi and KategorijeRadnici

CodePudding user response:

You just need to use the x:key attribute

<HierarchicalDataTemplate x:Key="LekoviTemplate" DataType="{x:Type local:Apoteka}" ItemsSource="{Binding KategorijeLekovi}">


<HierarchicalDataTemplate x:Key="RadniciTemplate" DataType="{x:Type local:Apoteka}" ItemsSource="{Binding KategorijeRadnici}">

Then set it in the tree view,

<TreeView ItemTemplate="{StaticResource LekoviTemplate}" ...

or

<TreeView ItemTemplate="{StaticResource RadniciTemplate}" ...
  • Related