我們都知道在WPF中鼠標滾輪可以控制垂直滾動條滾動,但沒有什麼屬性設置可以讓它控制水平滾動條滾動,所以我們需要自己去實現水平滾動。
首先,在ListBox的Mousewheel事件中獲得ListBox的滾動條,我發現MouseWheel事件不能被觸發,所以我們要這樣添加事件:
list.AddHandler(ListBox.MouseWheelEvent, new MouseWheelEventHandler(list_MouseWheel), true);
然後我們需要寫一個方法獲得LisBox的ScrollViewer:
public static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
{
if (obj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is T)
{
return (T)child;
}
T childItem = FindVisualChild<T>(child);
if (childItem != null) return childItem;
}
}
return null;
}
在MouseWheel中寫:
private void list_MouseWheel(object sender, MouseWheelEventArgs e)
{
ItemsControl items = (ItemsControl)sender;
ScrollViewer scroll = FindVisualChild<ScrollViewer>(items);
if (scroll != null)
{
int d = e.Delta;
if (d > 0)
{
scroll.LineRight();
}
if (d < 0)
{
scroll.LineLeft();
}
scroll.ScrollToTop();
}
}
其中,根據鼠標滾輪的變量值可以獲得鼠標滾輪的滾動方向,根據滾動方向設置滾動條的滾動方向。
由於默認情況下垂直滾動條由鼠標滾輪控制,所以我們可以讓垂直滾動條一直在最上方,然後隱藏垂直滾動條,就可以實現我們想要的效果!