2013-12-12 60 views
3

我正在做Windows Presentation Foundation中的一个项目。 我有一个ListBox其中每element是相同的height滚动滚动事件覆盖将向上/向下增加一个元素

我想实现的是:

  • 当我Mouse Wheel Scroll向上或向下我想ListBox总是由一个元素递增/递减视图。

我有什么权利现在:

  • 当我Mouse Wheel Scroll向上或向下它总是递增/递减一对夫妇(取决于屏幕高度)的元素。

有没有简单的解决方案呢?

感谢

+0

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

回答

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" /> 

希望可以帮助

+0

谢谢!这正是我所做的!除了我用'ItemsControl'代替'ScrollView'中包含的具有附加行为的'ListBox'。 谢谢! –