1. 程式人生 > >WPF TreeView BringIntoViewBehavior

WPF TreeView BringIntoViewBehavior

由於專案需要,需要能夠定位TreeView中的點,TreeView的節點數過多的情況下,即使找到了對應的節點並選中展示了,由於不在可視區域內,給使用者的感覺還是不好,因此設計如下的Behavior,來實現選中的TreeViewItem顯示在可見區域:

 1 using System;
 2 using System.Windows;
 3 using System.Windows.Controls;
 4 
 5 namespace Johar.Core
 6 {
 7     public static class BringIntoViewBehavior
 8     {
 9         public
static bool GetIsBringIntoViewWhenSelected(DependencyObject obj) 10 { 11 return (bool)obj.GetValue(IsBringIntoViewWhenSelectedProperty); 12 } 13 14 public static void SetIsBringIntoViewWhenSelected(DependencyObject obj, bool value) 15 { 16 obj.SetValue(IsBringIntoViewWhenSelectedProperty, value);
17 } 18 19 // Using a DependencyProperty as the backing store for IsBringIntoViewWhenSelected. This enables animation, styling, binding, etc... 20 public static readonly DependencyProperty IsBringIntoViewWhenSelectedProperty = 21 DependencyProperty.RegisterAttached("
IsBringIntoViewWhenSelected", 22 typeof(bool), typeof(BringIntoViewBehavior), 23 new FrameworkPropertyMetadata(false, new PropertyChangedCallback(OnIsBringIntoViewWhenSelected))); 24 25 private static void OnIsBringIntoViewWhenSelected(DependencyObject d, DependencyPropertyChangedEventArgs e) 26 { 27 TreeViewItem item = d as TreeViewItem; 28 if (item == null) 29 { 30 return; 31 } 32 33 if (e.NewValue is bool == false) 34 { 35 return; 36 } 37 38 if ((bool)e.NewValue) 39 { 40 item.Selected -= item_Selected; 41 item.Selected += item_Selected; 42 } 43 else 44 { 45 item.Selected -= item_Selected; 46 } 47 } 48 49 private static void item_Selected(object sender, RoutedEventArgs e) 50 { 59 TreeViewItem item = e.OriginalSource as TreeViewItem; 60 if (item != null) 61 { 62 item.BringIntoView(); 63 } 64 } 65 } 66 }

然後在TreeView中設定一下這個依賴屬性為True即可上述要求。