Bubbling scroll events from a ListView to its parent

前端 未结 8 1442
深忆病人
深忆病人 2020-11-28 06:25

In my WPF application I have a ListView whose ScrollViewer.VerticalScrollBarVisibility is set to Disabled. It is contained within a

8条回答
  •  爱一瞬间的悲伤
    2020-11-28 06:51

    You can also achieve the same thing using an attached behaviour. This has the advantage of not needing the System.Windows.Interactivity library. The logic has been taken from the other answers, only the implementation is different.

    public static class IgnoreScrollBehaviour
    {
        public static readonly DependencyProperty IgnoreScrollProperty = DependencyProperty.RegisterAttached("IgnoreScroll", typeof(bool), typeof(IgnoreScrollBehaviour), new PropertyMetadata(OnIgnoreScollChanged));
    
        public static void SetIgnoreScroll(DependencyObject o, string value)
        {
            o.SetValue(IgnoreScrollProperty, value);
        }
    
        public static string GetIgnoreScroll(DependencyObject o)
        {
            return (string)o.GetValue(IgnoreScrollProperty);
        }
    
        private static void OnIgnoreScollChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            bool ignoreScoll = (bool)e.NewValue;
            UIElement element = d as UIElement;
    
            if (element == null)
                return;
    
            if (ignoreScoll)
            {
                element.PreviewMouseWheel += Element_PreviewMouseWheel;
            }
            else
            {
                element.PreviewMouseWheel -= Element_PreviewMouseWheel;
            }
        }
    
        private static void Element_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
        {
            UIElement element = sender as UIElement;
    
            if (element != null)
            {
                e.Handled = true;
    
                var e2 = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta);
                e2.RoutedEvent = UIElement.MouseWheelEvent;
                element.RaiseEvent(e2);
            }
        }
    }
    

    And then in the XAML:

    
    
    
        
    
            
                
                    
                        ...
                    
                
            
        
    
    
    
       ...
    
    
    
    

提交回复
热议问题