【问题标题】:Wheel scroll event override to increment one element up/down滚轮滚动事件覆盖以向上/向下增加一个元素
【发布时间】:2013-12-12 12:22:22
【问题描述】:

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

我想要实现的是:

  • 当我 Mouse Wheel Scroll 向上或向下时,我希望 ListBox 始终以一个元素递增/递减视图。

我现在拥有的:

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

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

谢谢

【问题讨论】:

  • 您必须能够禁用滚动但捕获滚动事件,然后使用JQuery 或类似方法,然后将您的项目滚动到您声明的预定义高度。不过不要问我例子:)

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


【解决方案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" />

希望对你有帮助

【讨论】:

  • 谢谢!这正是我所做的!除了我使用了ItemsControl 而不是ListBox 包裹在带有附加行为的ScrollView 中。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多