|
| 1 | +using System.Windows.Controls; |
| 2 | +using System.Windows.Input; |
| 3 | +using System.Windows.Media; |
| 4 | + |
| 5 | +namespace Stack_Solver.Helpers.Behaviors; |
| 6 | + |
| 7 | +/// <summary> |
| 8 | +/// Attached behavior that forwards mouse wheel events to the nearest scrollable parent <see cref="ScrollViewer"/>. |
| 9 | +/// Use this when nested controls (DataGrid, NumberBox, etc.) consume wheel events and prevent parent scrolling. |
| 10 | +/// </summary> |
| 11 | +public static class ParentScrollBehavior |
| 12 | +{ |
| 13 | + public static readonly DependencyProperty EnabledProperty = |
| 14 | + DependencyProperty.RegisterAttached( |
| 15 | + "Enabled", |
| 16 | + typeof(bool), |
| 17 | + typeof(ParentScrollBehavior), |
| 18 | + new PropertyMetadata(false, OnEnabledChanged)); |
| 19 | + |
| 20 | + public static bool GetEnabled(DependencyObject obj) => (bool)obj.GetValue(EnabledProperty); |
| 21 | + public static void SetEnabled(DependencyObject obj, bool value) => obj.SetValue(EnabledProperty, value); |
| 22 | + |
| 23 | + private static void OnEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) |
| 24 | + { |
| 25 | + if (d is not UIElement element) |
| 26 | + return; |
| 27 | + |
| 28 | + if ((bool)e.NewValue) |
| 29 | + { |
| 30 | + element.AddHandler(UIElement.PreviewMouseWheelEvent, new MouseWheelEventHandler(OnPreviewMouseWheel), handledEventsToo: true); |
| 31 | + } |
| 32 | + else |
| 33 | + { |
| 34 | + element.RemoveHandler(UIElement.PreviewMouseWheelEvent, new MouseWheelEventHandler(OnPreviewMouseWheel)); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + private static void OnPreviewMouseWheel(object sender, MouseWheelEventArgs e) |
| 39 | + { |
| 40 | + if (FindScrollableParent(sender as DependencyObject) is { } scrollViewer) |
| 41 | + { |
| 42 | + scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset - e.Delta); |
| 43 | + e.Handled = true; |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + private static ScrollViewer? FindScrollableParent(DependencyObject? element) |
| 48 | + { |
| 49 | + var parent = element is null ? null : VisualTreeHelper.GetParent(element); |
| 50 | + |
| 51 | + while (parent is not null) |
| 52 | + { |
| 53 | + if (parent is ScrollViewer sv && CanScroll(sv)) |
| 54 | + return sv; |
| 55 | + |
| 56 | + parent = VisualTreeHelper.GetParent(parent); |
| 57 | + } |
| 58 | + |
| 59 | + return null; |
| 60 | + } |
| 61 | + |
| 62 | + private static bool CanScroll(ScrollViewer sv) => |
| 63 | + sv.ScrollableHeight > 0 || |
| 64 | + (sv.VerticalScrollBarVisibility != ScrollBarVisibility.Disabled && |
| 65 | + sv.ComputedVerticalScrollBarVisibility == Visibility.Visible); |
| 66 | +} |
0 commit comments