0
votes

Trying to build a WPF TreeView control which can contain another data bound control inside it. Here's the XAML:

<TreeView temsSource="{Binding DocumentCategories}">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding DocumentCategory1}">
            <TextBlock FontWeight="Bold" Text="{Binding Description}"></TextBlock>

            <HierarchicalDataTemplate.ItemTemplate>
                <DataTemplate>
                    <ListView ItemsSource="{Binding Documents}">
                        <TextBlock FontWeight="Bold" Text="{Binding Name}"></TextBlock>
                    </ListView>
                </DataTemplate>
            </HierarchicalDataTemplate.ItemTemplate>

        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

The DocumentCategories data is recursive - each item in the list has a DocumentCategory1 collection of DocumentCategories which has its own DocumentCategory1 collection and so forth.

Without the ListView inside it, this works just fine. However, when you add the ListView the TreeView renders ok but when you try and open one of the nodes, the application crashes with the error:

Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead

I'm not entirely sure which ItemsSource this is referring to - that of the TreeView or the ListView. I presume the latter, and that the problem is being caused by the fact that the binding isn't actually happening until after the node is opened.

I've tried changing both DocumentCateegories and Documents from List to an ObservableCollection, which seems to be a common fix for this error - but it still behaves the same.

Is it possible to have another databound control inside a TreeView, and if so, how?

1

1 Answers

1
votes

There is the DataTemplate of the ListView missing.

Currently the following Element is interpreted as an actual ListView Element:

<TextBlock FontWeight="Bold" Text="{Binding Name}"></TextBlock>

And as you already bound the ListView's ItemSource the error occurs, when the view is trying to add the "TextBlock" as an item of the ListView.

Just change it to the following:

<ListView ItemsSource="{Binding Documents}">
  <ListView.ItemTemplate>
    <DataTemplate>
      <TextBlock FontWeight="Bold" Text="{Binding Name}"></TextBlock>
    </DataTemplate>
  </ListView.ItemTemplate>
</ListView>