欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

WPF TreeView BringIntoViewBehavior

程序员文章站 2022-03-26 08:55:13
由于项目需要,需要能够定位TreeView中的点,TreeView的节点数过多的情况下,即使找到了对应的节点并选中展示了,由于不在可视区域内,给用户的感觉还是不好,因此设计如下的Behavior,来实现选中的TreeViewItem显示在可见区域: 然后在TreeView中设置一下这个依赖属性为Tr ......

由于项目需要,需要能够定位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即可上述要求。