如果列表中没有足够的项目,WPF ListBox按需加载项目

时间:2017-05-02 17:36:58

标签: c# wpf listbox

我试图实现逻辑以按需加载ListBox中的项目。每当用户使用滚动条或鼠标滚轮滚动时,它将检查是否有更多数据并加载它。我遇到的唯一问题是没有足够的项来填充ListBox,因此ScrollBar不可见,因此不会调用MouseWheel事件和ScrollViewer.VerticalOffsetProperty ValueChanged事件处理程序。

  static void AssignCommand(object sender, RoutedEventArgs e)
        {
            FrameworkElement element = (FrameworkElement)sender;
            element.Loaded -= AssignCommand;

            ScrollViewer scrollViewer = GetDescendantByType<ScrollViewer>(element);
            if (scrollViewer == null)
            {
                throw new InvalidOperationException("ScrollViewer not found.");
            }

            element.MouseWheel += delegate
            {
                // listbox not called
            };

            scrollViewer.MouseWheel += delegate
            {
                // scrollviewer not called
                var visibility = scrollViewer.ComputedVerticalScrollBarVisibility;
                if (visibility == Visibility.Collapsed)
                {
                    //try to fetch data
                }
            };

            var dpd = DependencyPropertyDescriptor.FromProperty(ScrollViewer.VerticalOffsetProperty, typeof(ScrollViewer));
            dpd.AddValueChanged(scrollViewer, delegate
            {
                bool atBottom = scrollViewer.VerticalOffset
                                    >= scrollViewer.ScrollableHeight;

                if (atBottom)
                {
                    var atEnd = GetAtEndCommand(element);
                    atEnd?.Execute(null);
                }
            });
        }

我很惊讶ListBox.MouseWheel事件未被调用,即使它没有被底层ScrollViewer处理。我想利用ComputedVerticalScrollBarVisibility,如果它不可见,那么它应该在用户滚动时尝试获取数据。

1 个答案:

答案 0 :(得分:0)

答案是PreviewMouseWheel

 scrollViewer.PreviewMouseWheel += delegate
            {
                var visibility = scrollViewer.ComputedVerticalScrollBarVisibility;
                if (visibility == Visibility.Collapsed)
                {
                    //try to fetch data
                }
            };