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

xaml代码:

1
2
3
4
5
<ItemsPanelTemplate x:Key="ItemsPanelTemplate1">
  <VirtualizingStackPanel Orientation="Horizontal" IsItemsHost="True"/>
</ItemsPanelTemplate>

  

1
2
3
4
5
6
7
8
<ListBox x:Name="listbox"
                             ItemsPanel="{DynamicResource ItemsPanelTemplate1}"
                             ScrollViewer.CanContentScroll="False" 
                             ScrollViewer.PanningMode="HorizontalOnly" 
                             ItemContainerStyle="{DynamicResource ListBoxItemStyleGroup1}"
                             HorizontalContentAlignment="Center"
                             ScrollViewer.HorizontalScrollBarVisibility="Hidden">
</ListBox>

cs代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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就可以横向滚动了

posted @   刺眼  阅读(1205)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示