David
David

Reputation: 413

Unselecting databound objects in a WPF treeview

I'm working on a WPF application where I have 2 TreeViews. Both have a collection of ViewModel objects as their ItemsSource. I'm trying to make it so that when the user selects an item in one TreeView, the other's selection is changed to null.

However, I noticed that the actual items in the TreeView are of the type SomethingViewModel and not TreeViewItem. This means they have no IsSelected property. I've tried adding an IsSelected property to the ViewModel objects and binding the property to the TreeViewItem template I'm using, but that doesn't seem to work.

XAML:

<TreeView x:Name="trvMaterials" SelectedItemChanged="trvMaterials_SelectedItemChanged" ItemsSource="{Binding MaterialListViewModel.MaterialViewModels}">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding MaterialVariants}">
            <TreeViewItem Header="{Binding InternalName, Mode=OneWay}" IsSelected="{Binding IsSelected}"></TreeViewItem>
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

C#:

public bool IsSelected
{
    get { return isSelected; }
    set { isSelected = value; RaisePropertyChanged("IsSelected"); }
}

How can I get this functionality to work? Please keep in mind that I'm new to WPF and MVVM.

Thanks!

Upvotes: 0

Views: 57

Answers (1)

Nitin Purohit
Nitin Purohit

Reputation: 18580

Don't bind IsSelected like you did. Add ItemContainerStyle like below:

<TreeView x:Name="trvMaterials" SelectedItemChanged="trvMaterials_SelectedItemChanged" ItemsSource="{Binding MaterialListViewModel.MaterialViewModels}">
<TreeView.ItemContainerStyle>
    <Style TargetType="TreeViewItem">
      <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
    </Style>
  </TreeView.ItemContainerStyle>
 <TreeView.ItemTemplate>
  <HierarchicalDataTemplate ItemsSource="{Binding MaterialVariants}">
    <TextBlock Text="{Binding InternalName, Mode=OneWay}"></TextBlock >
  </HierarchicalDataTemplate>
 </TreeView.ItemTemplate>
</TreeView>

Upvotes: 1

Related Questions