R – WPF Treeview – Syncing with a ViewModel

listboxsynchronizationtreeviewwpf

I have a window that contains a grid with two columns.
the first column is filled with a TreeView.
the second column is filled with a ListBox.

Both controls are bound to a CollectionView that wraps my data – an ObserveableCollection of my data class type. The ListBox is set to keep syncronized with the view (SyncToCurrentItem etc). I also implemented a custom ListBoxItem that calls BringIntoView and Focus on a newly selected item.

However, The Treeview does not support such operations against the CollectionView.

Is there a way to achieve this? What i want to be able to do is to select something in the tree, and have it selected as well in the ListBox.

Thanks in advance for any help.

Best Answer

To keep a ListBox in sync with the TreeView, you'll need to bind it's SelectedItem to the TreeView's SelectedItem. The Binding Mode needs to be OneWay since the TreeView SelectedItem is readonly. Here's an example:

<TreeView Name="CategoryTreeView" DockPanel.Dock="Top" MinHeight="50" MinWidth="100">
     <TreeView.ItemTemplate>
         <HierarchicalDataTemplate DataType="x:Type local:Category"
             ItemsSource="{Binding Path=Children}">
             <TextBlock Text="{Binding Path=Name}"></TextBlock>
         </HierarchicalDataTemplate>
     </TreeView.ItemTemplate>
 </TreeView>
 <ListBox Name="CategoryList" SelectedItem="{Binding ElementName=CategoryTreeView, Path=SelectedItem, Mode=OneWay}"/>

I created a basic Category class with a Name and Children (List). It's a little more work to get the TreeView updating with the ListBox, but it's doable. Let me know if you're trying to go both ways.

Related Topic