Search code examples
wpfmvvmtreeviewdatatemplate

TreeView: child node's VM being affected by parent selection


What's wrong with the following TreeView setup? Setting selected property of parent node's VM toggles child node's selected property.

<TreeView ItemsSource="{Binding Documents}">
  <TreeView.ItemContainerStyle>
    <Style TargetType="TreeViewItem">
      <Setter Property="IsExpanded" Value="True" />
      <Setter Property="IsSelected" Value="{Binding selected}" />
    </Style>
  </TreeView.ItemContainerStyle>

  <TreeView.ItemTemplate>
    <HierarchicalDataTemplate ItemsSource="{Binding descriptions}">
      <HierarchicalDataTemplate.ItemContainerStyle>
        <Style TargetType="TreeViewItem">
          <Setter Property="IsSelected" Value="{Binding selected}" />
        </Style>
      </HierarchicalDataTemplate.ItemContainerStyle>
      <HierarchicalDataTemplate.ItemTemplate>
        <DataTemplate>
          <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding name}" />
          </StackPanel>
        </DataTemplate>
      </HierarchicalDataTemplate.ItemTemplate>
        <TextBlock Text="{Binding name}" />
      </StackPanel>
    </HierarchicalDataTemplate>
  </TreeView.ItemTemplate>
</TreeView>

The VM objects look like this:

public class DocumentVM : ObservableObject
{
    private string _name;
    public string name
    {
      get { return _name; }
      set { Set(ref _name, value); }
    }

    private bool _selected = false;
    public bool selected
    {
      get { return _selected; }
      set { Set(ref _selected, value); }
    }
}

DescriptionVM is very similar.

So for example, if I run the following two lines:

MyVM.Documents[1].descriptions[0].selected = true;
MyVM.Documents[1].selected = true;

First line sets first child of second document to selected, whereas the second line sets first document node to select, but sets first child of second document to unselected. I'm sure this is something wrong with the DataTemplates I'm using there, but can't figure out what that is.


Solution

  • By default, the WPF TreeView doesn't support multiple selection, so the second select will automatically unselect the first item.

    There are ways to handle this - look at this answer.