滚动滚动事件覆盖以向上/向下递增一个元素

时间:2013-12-12 12:22:23

标签: c# .net wpf visual-studio-2010

我在Windows Presentation Foundation中做了一个项目。 我有一个ListBox,其中每element都是height

我想要达到的目标是:

  • 当我Mouse Wheel Scroll向上或向下时,我希望ListBox总是通过一个元素递增/递减视图。

我现在拥有的东西:

  • 当我Mouse Wheel Scroll向上或向下时,它总是增加/减少几个(取决于屏幕高度)元素。

对此有什么简单的解决方案吗?

由于

1 个答案:

答案 0 :(得分:1)

简单地快速破解(这意味着你可以以更好的方式做到这一点,也许是附加行为)

private void OnPreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
  var lb = sender as ListBox;
  if (lb != null) {
    // get or store scrollviewer
    if (lb.Tag == null) {
      lb.Tag = GetDescendantByType(lb, typeof(ScrollViewer)) as ScrollViewer;
    }
    var lbScrollViewer = lb.Tag as ScrollViewer;
    if (lbScrollViewer != null) {
      if (e.Delta < 0) {
        lbScrollViewer.LineDown();
      } else {
        lbScrollViewer.LineUp();
      }
      e.Handled = true;
    }
  }
}

GetDescendantByType方法

public static Visual GetDescendantByType(Visual element, Type type)
{
  if (element == null) {
    return null;
  }
  if (element.GetType() == type) {
    return element;
  }
  Visual foundElement = null;
  if (element is FrameworkElement) {
    (element as FrameworkElement).ApplyTemplate();
  }
  for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++) {
    Visual visual = VisualTreeHelper.GetChild(element, i) as Visual;
    foundElement = GetDescendantByType(visual, type);
    if (foundElement != null) {
      break;
    }
  }
  return foundElement;
}

使用

<ListBox PreviewMouseWheel="OnPreviewMouseWheel" />

希望有所帮助

相关问题