Created
November 30, 2022 06:55
-
-
Save Platonenkov/e93ad0518a866eb7f5e2c188a72cc24e to your computer and use it in GitHub Desktop.
Mouse scroll in a scroll viewer with a datagrid or listbox and additional UI elements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class TopMouseScrollPriorityBehavior | |
{ | |
public static bool GetTopMouseScrollPriority(ScrollViewer obj) | |
{ | |
return (bool)obj.GetValue(TopMouseScrollPriorityProperty); | |
} | |
public static void SetTopMouseScrollPriority(ScrollViewer obj, bool value) | |
{ | |
obj.SetValue(TopMouseScrollPriorityProperty, value); | |
} | |
public static readonly DependencyProperty TopMouseScrollPriorityProperty = | |
DependencyProperty.RegisterAttached("TopMouseScrollPriority", typeof(bool), typeof(TopMouseScrollPriorityBehavior), new PropertyMetadata(false, OnPropertyChanged)); | |
private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) | |
{ | |
var scrollViewer = d as ScrollViewer; | |
if (scrollViewer == null) | |
throw new InvalidOperationException($"{nameof(TopMouseScrollPriorityBehavior)}.{nameof(TopMouseScrollPriorityProperty)} can only be applied to controls of type {nameof(ScrollViewer)}"); | |
if (e.NewValue == e.OldValue) | |
return; | |
if ((bool)e.NewValue) | |
scrollViewer.PreviewMouseWheel += ScrollViewer_PreviewMouseWheel; | |
else | |
scrollViewer.PreviewMouseWheel -= ScrollViewer_PreviewMouseWheel; | |
} | |
private static void ScrollViewer_PreviewMouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e) | |
{ | |
var scrollViewer = (ScrollViewer)sender; | |
scrollViewer.ScrollToVerticalOffset(scrollViewer.VerticalOffset - e.Delta); | |
e.Handled = true; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<ScrollViewer b:TopMouseScrollPriorityBehavior.TopMouseScrollPriority="True" VerticalScrollBarVisibility="Auto" Margin="5" PanningMode="VerticalFirst"> | |
<DataGrid ScrollViewer.PanningMode="None" ItemsSource="{Binding Items}" /> | |
</ScrollViewer> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment