我试图找出如何做某件应该很简单的事情。
我想要的是每当滚动 ListBox 控件时触发一个事件。ListBox 是动态创建的,因此我需要一种从代码后台实现它的方法(但欢迎使用 XAML 解决方案,因为它给了我一个起点)。
感谢您提供任何想法。
我想要的是每当滚动 ListBox 控件时触发一个事件。ListBox 是动态创建的,因此我需要一种从代码后台实现它的方法(但欢迎使用 XAML 解决方案,因为它给了我一个起点)。
感谢您提供任何想法。
<ListBox Name="listBox" ScrollViewer.ScrollChanged="listBox_ScrollChanged"/>
更新
这可能是您在代码后端需要的内容:
List<ScrollBar> scrollBarList = GetVisualChildCollection<ScrollBar>(listBox);
foreach (ScrollBar scrollBar in scrollBarList)
{
if (scrollBar.Orientation == Orientation.Horizontal)
{
scrollBar.ValueChanged += new RoutedPropertyChangedEventHandler<double>(listBox_HorizontalScrollBar_ValueChanged);
}
else
{
scrollBar.ValueChanged += new RoutedPropertyChangedEventHandler<double>(listBox_VerticalScrollBar_ValueChanged);
}
}
使用GetVisualChildCollection实现:
public static List<T> GetVisualChildCollection<T>(object parent) where T : Visual
{
List<T> visualCollection = new List<T>();
GetVisualChildCollection(parent as DependencyObject, visualCollection);
return visualCollection;
}
private static void GetVisualChildCollection<T>(DependencyObject parent, List<T> visualCollection) where T : Visual
{
int count = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < count; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(parent, i);
if (child is T)
{
visualCollection.Add(child as T);
}
else if (child != null)
{
GetVisualChildCollection(child, visualCollection);
}
}
}