我试图弄清楚如何做(应该)很简单的事情。
我想要的是让ListBox控件滚动时触发事件。 ListBox是动态创建的,因此我需要一种从背后的代码中进行操作的方法(不过,XAML解决方案也受到赞赏,因为它为我提供了一些起点)。
预先感谢您的任何想法。
最佳答案
在XAML中,您可以访问ScrollViewer并添加如下事件:
<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);
}
}
}
关于WPF ListBox OnScroll事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4139341/