如何在ListBox中禁用ScrollViewer?

lev*_*ovd 11 wpf xaml listbox scrollviewer

我有一个ListBox.它有内部ScrollViewer,所以我可以用鼠标滚轮滚动ListBox内容.它工作正常,直到我设置包含另一个ListBox的项目模板(事实上,我有4个嵌套的ListBoxes =)).问题是内部ListBox的ScrollViewer窃取了转动事件.有没有简单的方法可以防止这种行为?


我有ListBox和ItemContainerStyle,如下所示:

<Style x:Key="ListBoxItemStyle" TargetType="{x:Type ListBoxItem}">
    <Setter Property="BorderBrush" Value="Black"/>
     ... 
</Style>
<ListBox ItemContainerStyle="{StaticResource ListBoxItemStyle}" />
Run Code Online (Sandbox Code Playgroud)

如何在这样的资源中为ItemContainer的项边框设置样式?据我所知,ContentPresenter是ItemsControl的项容器.但它没有边框,所以我无法设计它.

Mat*_*ton 50

您可以通过将其控件模板更改为更简单的方法来删除ScrollViewera ListBox:

<ListBox>
    <ListBox.Template>
        <ControlTemplate>
            <ItemsPresenter />
        </ControlTemplate>
    </ListBox.Template>
    ...
</ListBox>
Run Code Online (Sandbox Code Playgroud)

但是,我质疑嵌套ListBoxes的价值.请记住,每个ListBox都是一个选择器,并具有"选择"项目的概念.在所选项目内的所选项目中选择项目是否真的有意义?

我建议将"内部"更改ListBoxes为简单,ItemsControls以便嵌套列表不能包含所选项.这将使用户体验更加简单.您可能仍需要以ItemsControls相同的方式重新模拟内部以移除滚动条,但至少用户不会对哪个项目被"选中"感到困惑.


teq*_*cat 5

您可以通过捕获XAML中的滚动事件来禁用窃取滚动事件:

<ListBox PreviewMouseWheel="ScrollViewer_PreviewMouseWheel">
Run Code Online (Sandbox Code Playgroud)

并在下面的代码中重新发布:

private void ScrollViewer_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
    {
        if (sender is ListBox && !e.Handled)
        {
            e.Handled = true;
            var eventArg = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta);
            eventArg.RoutedEvent = UIElement.MouseWheelEvent;
            eventArg.Source = sender;
            var parent = ((Control)sender).Parent as UIElement;
            parent.RaiseEvent(eventArg);
        }
    }
Run Code Online (Sandbox Code Playgroud)

该解决方案正是针对ListBox的,它帮助我实现了ListView。

我在这里找到了这个解决方案:

https://social.msdn.microsoft.com/Forums/vstudio/zh-CN/3a3bb6b0-e088-494d-8ef2-60814415fd89/swallowing-mouse-scroll?forum=wpf