我想将 MouseWheel 的处理程序添加到 ComboBox,但我不知道如何操作。
原因是我在 ScrollViewer 内的 DataGrid 内的 ComboBox 上遇到滚动问题,请参阅here,我想尝试一下。我已经有了处理 ScrollViewer 和 DataGrid 的 MouseWheel 的代码,但还没有处理 ComboBox 的代码。
<ComboBox PreviewMouseWheel="theComboBox_PreviewMouseWheel"
背后代码:
private void theScrollViewer_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
if (sender is ScrollViewer scrollView)
{
scrollView.UpdateLayout();
scrollView.ScrollToVerticalOffset(scrollView.VerticalOffset - e.Delta);
e.Handled = true;
}
}
private void theDataGrid_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
var args = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta);
args.RoutedEvent = ScrollViewer.MouseWheelEvent;
theScrollViewer.RaiseEvent(args);
}
/// <summary>
/// The hypothetical scroll event handler, on the ComboBox,
/// to make the ComboBox scrollable
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void theComboBox_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
if (sender is ComboBox cb)
{
var args = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta);
args.RoutedEvent = ScrollViewer.MouseWheelEvent;
//cb.ItemsPanel.RaiseEvents(args);//cb has no such property
//cb.ScrollToVerticalOffset(cb.VerticalOffset - e.Delta);//cb has no such property
//e.Handled = true;
}
}
您可以使用
ComboBox
类获取对 ScrollViewer
内部 VisualTreeHelper
的引用,然后访问其属性和方法来设置偏移量:
private void theComboBox_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
{
if (sender is ComboBox cb && e.OriginalSource is DependencyObject depObj)
{
ScrollViewer scrollViewer = FindParent<ScrollViewer>(depObj);
...
}
}
private static T FindParent<T>(DependencyObject dependencyObject) where T : DependencyObject
{
var parent = VisualTreeHelper.GetParent(dependencyObject);
if (parent == null)
return null;
var parentT = parent as T;
return parentT ?? FindParent<T>(parent);
}