WPF ListBox横向布局并支持鼠标横向滚动

xaml代码:

<ItemsPanelTemplate x:Key="ItemsPanelTemplate1">
  <VirtualizingStackPanel Orientation="Horizontal" IsItemsHost="True"/>
</ItemsPanelTemplate>

 

  

<ListBox x:Name="listbox" 
                             ItemsPanel="{DynamicResource ItemsPanelTemplate1}" 
                             ScrollViewer.CanContentScroll="False"  
                             ScrollViewer.PanningMode="HorizontalOnly"  
                             ItemContainerStyle="{DynamicResource ListBoxItemStyleGroup1}"
                             HorizontalContentAlignment="Center" 
                             ScrollViewer.HorizontalScrollBarVisibility="Hidden">
</ListBox>

cs代码:

public Demo()
{
            InitializeComponent();
            listbox.AddHandler(ListBox.MouseWheelEvent, new MouseWheelEventHandler(ListBox_MouseWheel), true);
}

private void ListBox_MouseWheel(object sender, MouseWheelEventArgs e)
{
            ItemsControl items = (ItemsControl)sender;
            ScrollViewer scroll = FindVisualChild<ScrollViewer>(items);
            if (scroll != null)
            {
                int d = e.Delta;
                int currentNum = 0;
                var horOffset = (int)Math.Round(scroll.HorizontalOffset);
                if (d > 0)
                {
                    scroll.LineLeft();
                    currentNum = horOffset / (int)ListSignal.ActualWidth + 1;
                }
                if (d < 0)
                {

                    scroll.LineRight();
                    currentNum = horOffset / (int)ListSignal.ActualWidth + 1;
                }
                scroll.ScrollToTop();
            }
}

 

这样ListBox就可以横向滚动了

原文地址:https://www.cnblogs.com/cuigzh/p/14299103.html