
正文
WPF TreeView BringIntoViewBehavior
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
由于项目需要,需要能够定位TreeView中的点,TreeView的节点数过多的情况下,即使找到了对应的节点并选中展示了,由于不在可视区域内,给用户的感觉还是不好,因此设计如下的Behavior,来实现选中的TreeViewItem显示在可见区域:
using System;
using System.Windows;
using System.Windows.Controls; namespace Johar.Core
{
public static class BringIntoViewBehavior
{
public static bool GetIsBringIntoViewWhenSelected(DependencyObject obj)
{
return (bool)obj.GetValue(IsBringIntoViewWhenSelectedProperty);
} public static void SetIsBringIntoViewWhenSelected(DependencyObject obj, bool value)
{
obj.SetValue(IsBringIntoViewWhenSelectedProperty, value);
} // Using a DependencyProperty as the backing store for IsBringIntoViewWhenSelected. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsBringIntoViewWhenSelectedProperty =
DependencyProperty.RegisterAttached("IsBringIntoViewWhenSelected",
typeof(bool), typeof(BringIntoViewBehavior),
new FrameworkPropertyMetadata(false, new PropertyChangedCallback(OnIsBringIntoViewWhenSelected))); private static void OnIsBringIntoViewWhenSelected(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
TreeViewItem item = d as TreeViewItem;
if (item == null)
{
return;
} if (e.NewValue is bool == false)
{
return;
} if ((bool)e.NewValue)
{
item.Selected -= item_Selected;
item.Selected += item_Selected;
}
else
{
item.Selected -= item_Selected;
}
} private static void item_Selected(object sender, RoutedEventArgs e)
{
TreeViewItem item = e.OriginalSource as TreeViewItem;
if (item != null)
{
item.BringIntoView();
}
}
}
}
然后在TreeView中设置一下这个依赖属性为True即可上述要求。








