views:

684

answers:

1

Hi everyone.

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.

+2  A: 

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.

Mark Synowiec
Hi, Thanks for the snippet. I don't essentially need it both ways, but if the tree is responsible for making the selection, I need a way to stop the ListBox from changing that selection, thus over-writing the binding (since its OneWay) and losing the sync. Any ideas?
Ran Sagy
You might want to add a handler for the selectionchanged event on the TreeView, and set the Binding's UpdateSourceTrigger to Explicit. In the selectionchanged event, you'd need to grab the BindingExpression and call UpdateSource or UpdateTarget method on it depending on which way the binding is set up, but then you could wrap the call in whatever logic you need to turn it on/off.
Mark Synowiec
Oh, here's a link to an msdn example:http://msdn.microsoft.com/en-us/library/ms771706.aspx
Mark Synowiec