TreeView BringIntoView with MVVM

I want the user to be able to search for items in a TreeView. After entering the search text, TreeViewItem should scroll in the view.

Right now I am using the MVVM template for TreeView, for TreeViewItems and MainView.

What do I need to do to get BringIntoView functionality using MVVM? Is there any property that I can bind? (there was something like FirstVisibileItem in MFC)

We saw a "solution" with behavior. Is it really necessary?

+6
source share
2 answers

The problem can be solved through behavior.

This CodeProject article describes it very well, and it works out of the box.

+5
source

In accordance with the indicated code draft article, here is an example code that shows how to customize the behavior and how to integrate the behavior in XAML.

Behavior customization:

/// <summary> /// Exposes attached behaviors that can be /// applied to TreeViewItem objects. /// </summary> public static class TreeViewItemBehavior { #region IsBroughtIntoViewWhenSelected public static bool GetIsBroughtIntoViewWhenSelected(TreeViewItem treeViewItem) { return (bool)treeViewItem.GetValue(IsBroughtIntoViewWhenSelectedProperty); } public static void SetIsBroughtIntoViewWhenSelected( TreeViewItem treeViewItem, bool value) { treeViewItem.SetValue(IsBroughtIntoViewWhenSelectedProperty, value); } public static readonly DependencyProperty IsBroughtIntoViewWhenSelectedProperty = DependencyProperty.RegisterAttached( "IsBroughtIntoViewWhenSelected", typeof(bool), typeof(TreeViewItemBehavior), new UIPropertyMetadata(false, OnIsBroughtIntoViewWhenSelectedChanged)); static void OnIsBroughtIntoViewWhenSelectedChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e) { TreeViewItem item = depObj as TreeViewItem; if (item == null) return; if (e.NewValue is bool == false) return; if ((bool)e.NewValue) item.Selected += OnTreeViewItemSelected; else item.Selected -= OnTreeViewItemSelected; } static void OnTreeViewItemSelected(object sender, RoutedEventArgs e) { // Only react to the Selected event raised by the TreeViewItem // whose IsSelected property was modified. Ignore all ancestors // who are merely reporting that a descendant Selected fired. if (!Object.ReferenceEquals(sender, e.OriginalSource)) return; TreeViewItem item = e.OriginalSource as TreeViewItem; if (item != null) item.BringIntoView(); } #endregion // IsBroughtIntoViewWhenSelected } 

Then integrate TreeViewItemBehavior in XAML:

 <TreeView.ItemContainerStyle> <Style TargetType="{x:Type TreeViewItem}"> <Setter Property="local:TreeViewItemBehavior.IsBroughtIntoViewWhenSelected" Value="True"/> </Style> </TreeView.ItemContainerStyle> 

Good luck :-)

+8
source

All Articles