这是 DependencyProperty 的变体,如果您不喜欢行为
public class IgnoreScrollingBehavior
{
public static readonly DependencyProperty IgnoreScrollingProperty =
DependencyProperty.RegisterAttached("IgnoreScrolling", typeof(bool),
typeof(IgnoreScrollingBehavior), new UIPropertyMetadata(false, OnIgnoreScrollingChanged));
public static bool GetIgnoreScrolling(UIElement uIElement)
{
return (bool)uIElement.GetValue(IgnoreScrollingProperty);
}
public static void SetIgnoreScrolling(UIElement uIElement, bool value)
{
uIElement.SetValue(IgnoreScrollingProperty, value);
}
private static void OnIgnoreScrollingChanged(DependencyObject depOpj, DependencyPropertyChangedEventArgs e)
{
if (depOpj is not UIElement item)
{
return;
}
if (e.NewValue is bool boolean)
{
if (boolean)
{
item.PreviewMouseWheel += OnPreviewMouseWheel;
}
else
{
item.PreviewMouseWheel -= OnPreviewMouseWheel;
}
}
}
private static void OnPreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
e.Handled = true;
MouseWheelEventArgs eventArg = new(e.MouseDevice, e.Timestamp, e.Delta)
{
RoutedEvent = UIElement.MouseWheelEvent,
Source = sender
};
UIElement parent = ((Control)sender).Parent as UIElement;
parent.RaiseEvent(eventArg);
}
}
这就是它的使用方式
<Listbox b:IgnoreScrollingBehavior.IgnoreScrolling="True".../>