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即可上述要求。

posted @ 2018-10-15 17:24 Johar 阅读(...) 评论(...) 编辑 收藏