首页 > 代码库 > WPF获取控件内部的ScrollViewer,并控制ScrollViewer操作
WPF获取控件内部的ScrollViewer,并控制ScrollViewer操作
//获取内部 ScrollViewer方法
public static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
{
if (obj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is T)
{
return (T)child;
}
T childItem = FindVisualChild<T>(child);
if (childItem != null) return childItem;
}
}
return null;
}
//通过鼠标滑轮事件控制ScrollViewer滚动
private void list_MouseWheel(object sender, MouseWheelEventArgs e)
{
ItemsControl items = (ItemsControl)sender;
ScrollViewer scroll = FindVisualChild<ScrollViewer>(items);
if (scroll != null)
{
int d = e.Delta;
if (d > 0)
{
scroll.LineRight();
}
if (d < 0)
{
scroll.LineLeft();
}
scroll.ScrollToTop();
}
}