如何解决WPF中 ScrollViewer 内包含 TreeView 或者 ListBox 等控件时滚轮事件被劫持的问题

  • 以DataGrid为例,应先设置其横纵向的滚动条不可用
<DataGrid ScrollViewer.HorizontalScrollBarVisibility="Disabled" 
ScrollViewer.VerticalScrollBarVisibility="Disabled" />
  • 定义ScrollViewer的滚动事件
// scrollViewer的滚动事件
private void scrollViewer_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
    var eventArg = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta);
    eventArg.RoutedEvent = UIElement.MouseWheelEvent;
    eventArg.Source = e.Source;

    ScrollViewer scv = (ScrollViewer)sender;
    scv.RaiseEvent(eventArg);
    e.Handled = true;
}
  • 滚动事件跳转
// datagrid的滚动事件
private void DataGrid_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
    // 直接跳转至上述scrollViewer的滚动事件
    scrollViewer_PreviewMouseWheel(scrollViewer, e);
}

参考资料:

c# - Mouse scroll not working in a scroll viewer with a wpf datagrid and additional UI elements - Stack Overflow

相关推荐
©️2020 CSDN 皮肤主题: 鲸 设计师:meimeiellie 返回首页