陈仓主教头像
WPF 列表框(ListBox)控件详解与使用—WPF 中的控件(21)--列表框(ListBox)封面图

WPF 列表框(ListBox)控件详解与使用—WPF 中的控件(21)--列表框(ListBox)

WPF 列表框(ListBox)控件详解与使用

—WPF 中的控件(21)–列表框(ListBox)

控件 ListBox 显示用户可以从中选择的项集合。 ListBox 支持单个或多个选择,并提供键盘导航、滚动功能和数据绑定功能。 它通常用于用户需要从预定义选项中进行选择的窗体和应用程序中。

一句话定位:ListBox 是"可选中的列表",基类链为 ItemsControl → Selector → ListBox,容器类型为 ListBoxItem。它负责数据项的排列与选中状态管理,外观展示交给 ItemTemplate,两者分离是理解它的关键。 本文难点较多。建议初读后点赞收藏,以后有时间再细读或你的WPF编程较高后再说。

微软官方文档 ListBox 类


一、核心属性速查

分类成员说明
数据ItemsSource绑定数据集合;与 Items 互斥,同时使用会抛异常
数据Items直接内联子项(ListBoxItem 或任意对象)
数据DisplayMemberPath单字段显示,最省事的方案,与 ItemTemplate 二选一
数据ItemTemplate自定义每项外观(DataTemplate),多字段/图标走它
选中SelectedItem / SelectedValue当前选中项 / 按 SelectedValuePath 取到的值;SelectedItem 默认双向绑定
选中SelectedIndex选中项索引,-1 表示未选中
选中SelectedItems多选结果(IList,只读、非依赖属性,不能直接绑定)
选中SelectionModeSingle(默认)/ Multiple(点选切换)/ Extended(Ctrl、Shift 扩展)
外观ItemContainerStyle定制 ListBoxItem 的样式与模板(最常用)
外观ItemsPanel换布局面板(WrapPanel 可做多列,但会关闭虚拟化)
外观AlternationCount交替行数,配合 ItemsControl.AlternationIndex 做斑马纹
行为SelectionChanged选中变化事件,e.AddedItems / e.RemovedItems 给出增量
方法ScrollIntoView(item)滚动到指定项;虚拟化下定位容器前必须先调它

二、例程 1:最小可用示例(内联项 + 选中事件)

<!-- Window1.xaml -->
<Window x:Class="WpfListBoxDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:infra="clr-namespace:WpfListBoxDemo.Infrastructure"
        Title="WPF ListBox 详解示例" Height="800" Width="1120"
    <StackPanel Margin="12">
        <!-- SelectionMode 默认即 Single;显式写出便于阅读 -->
        <ListBox x:Name="lstFruit" Height="180"
                 SelectionMode="Single"
                 SelectionChanged="LstFruit_SelectionChanged">
            <!-- 直接写子项时,WPF 自动为其生成 ListBoxItem 容器 -->
            <!-- Tag 常用来挂业务主键(Id、编码),避免只靠显示文本反查 -->
            <ListBoxItem Content="苹果" Tag="apple"/>
            <ListBoxItem Content="香蕉" Tag="banana"/>
            <ListBoxItem Content="橙子" Tag="orange"/>
        </ListBox>

        <TextBlock x:Name="txtResult" Margin="0,8,0,0" Foreground="#666"/>
    </StackPanel>
</Window>

private void LstFruit_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    // sender 是 ListBox 本身;e.AddedItems / e.RemovedItems 是本次"增/删"的项
    var lb = (ListBox)sender;

    if (lb.SelectedItem is ListBoxItem item)
    {
        // 注意:这里因为 XAML 里写的是 ListBoxItem,所以 SelectedItem 的静态类型就是 ListBoxItem
        // 若 XAML 里直接写 <sys:String>苹果</sys:String>,SelectedItem 就是 string
        txtResult.Text = $"选中:{item.Content}(Tag={item.Tag})";
    }
    else
    {
        txtResult.Text = "未选中任何项";
    }
}

要点:SelectedItem 的运行时类型完全由数据源决定。混用"字符串项"和"ListBoxItem 项"是新手最常见的类型转换崩溃点。

简单解释:点击 ListBox的项 → SelectionChanged事件 → ListBox的SelectedItem属性获取(ListBoxItem类型)的选中项和(object类型)Tag值 → ListBoxItem类型的项和Tag值 转换为字符串类型显示。

三、例程 2:数据绑定(MVVM 标准姿势)

模型与 ViewModel

// 数据模型:只有需要"改一个字段就刷新界面"的属性才需要通知
public class Employee : INotifyPropertyChanged
{
    public int Id { get; set; }          // 不变字段,普通属性即可
	public string Dept { get; set; }     // 不变字段,普通属性即可
	
    private string _name;
    public string Name                      // 可变字段,必须发通知
    {
        get => _name;
        set { _name = value; OnPropertyChanged(); }
    }  
	
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string p = null)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(p));
}

public class MainViewModel : INotifyPropertyChanged
{
    // 用 ObservableCollection:增删项会自动刷新 ListBox
    // 用 List<T> 或普通数组:界面不会跟着变,这是最典型的"数据不刷新"事故
    public ObservableCollection<Employee> Employees { get; } = new()
    {
        new Employee { Id = 1, Name = "张三", Dept = "研发部" },
        new Employee { Id = 2, Name = "李四", Dept = "测试部" },
        new Employee { Id = 3, Name = "王五", Dept = "产品部" },
    };

    private Employee _current;
    public Employee Current
    {
        get => _current;
        set { _current = value; OnPropertyChanged(); }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName] string p = null)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(p));
}

三种展示方式

<!-- 方式 A:单字段,最省事。缺点是没法调样式、没法加图标 -->
<ListBox ItemsSource="{Binding Employees}"
         DisplayMemberPath="Name"
         SelectedItem="{Binding Current}"/>

<!-- 方式 B:模板,多字段/图标/状态点都靠它
     注意 SelectedItem 默认就是 TwoWay,不需要写 Mode=TwoWay -->
<ListBox ItemsSource="{Binding Employees}"
         SelectedItem="{Binding Current}"
         HorizontalContentAlignment="Stretch">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Name}" FontWeight="Bold" Width="70"/>
                <TextBlock Text="{Binding Dept}" Foreground="Gray"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

<!-- 方式 C:只关心"值"而不是整对象时,用 SelectedValuePath -->
<ListBox ItemsSource="{Binding Employees}"
         DisplayMemberPath="Name"
         SelectedValuePath="Id"
         SelectedValue="{Binding SelectedId}"/>

关键提醒:DisplayMemberPath 与 ItemTemplate 同时设置时以 ItemTemplate 为准(前者只是"没有模板时的默认模板")。实践中只用其一,不要两个都写。


四、例程 3:多选(Extended / Multiple)

<!-- Extended:Ctrl 点击加选、Shift 点击连选,直接单击会清掉之前的选择 -->
<ListBox x:Name="lstMulti" SelectionMode="Extended"
         ItemsSource="{Binding Employees}" DisplayMemberPath="Name"/>
<Button Content="查看已选" Click="BtnGetSelected_Click"/>
private void BtnGetSelected_Click(object sender, RoutedEventArgs e)
{
    // SelectedItems 是只读 IList,不能直接写 {Binding};MVVM 多选需自定义附加属性/行为
    var names = lstMulti.SelectedItems
                         .Cast<Employee>()
                         .Select(x => x.Name);

    MessageBox.Show(names.Any() ? string.Join("、", names) : "尚未选择");
}

// 若在 SelectionChanged 内部又去改选中项/ItemsSource,会触发重入:
private bool _updating;
private void Lst_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (_updating) return;      // 防重入闸门
    _updating = true;
    try
    {
        // 例如:选中"全部"时就批量选中其余项
    }
    finally { _updating = false; }
}
模式操作方式典型场景
Single单击即替换选中详情页主列表
ExtendedCtrl 加选、Shift 连选、单击清空桌面式文件/资源选择
Multiple不用按 Ctrl,点一下(选与不选)切换筛选条件、标签多选(更像复选框列表)

在后面的真实示例中采用MVVM方式。这也是业界的流行做法。

但是ListBox.SelectedItems 是 IList 类型的普通属性(不是依赖属性),所以 {Binding SelectedItems} 写不出来。业界通行做法是写这个附加的依赖属性: 把 ListBox 的选中项与 ViewModel 里的集合(实现 IList)互相同步。让 ListBox.SelectedItems 可以双向绑定。

用法: infra:ListBoxSelectionBinder.SelectedItems=“{Binding SelectedEmployees}”


五、例程 4:外观定制(选中高亮 + 斑马纹)

系统主题会自己绘制选中高亮,只改 Background 常被盖掉——自绘 ControlTemplate 最稳。

<ListBox ItemsSource="{Binding Employees}" AlternationCount="2"
         BorderThickness="1" BorderBrush="#DDD">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <!-- ListBox 默认 HorizontalContentAlignment=Left,设 Stretch 才能整行铺满 -->
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
            <Setter Property="Padding" Value="8,5"/>

            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListBoxItem">
                        <Border x:Name="bd"
                                Background="{TemplateBinding Background}"
                                Padding="{TemplateBinding Padding}">
                            <ContentPresenter/>
                        </Border>
                        <ControlTemplate.Triggers>
                            <!-- 悬停 -->
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter TargetName="bd" Property="Background" Value="#E5F1FB"/>
                            </Trigger>
                            <!-- 选中(模板触发器优先级高于 TemplateBinding,所以能覆盖斑马纹) -->
                            <Trigger Property="IsSelected" Value="True">
                                <Setter TargetName="bd" Property="Background" Value="#0078D4"/>
                                <Setter TargetName="bd" Property="TextElement.Foreground" Value="White"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>

            <!-- 斑马纹:用 AlternationIndex,不要手写行号 -->
            <Style.Triggers>
                <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                    <Setter Property="Background" Value="#F7F7F7"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

注意:若同时开启容器回收(VirtualizationMode="Recycling"),交错索引会随容器复用出现错位,斑马纹可能不稳定;数据量大时优先保证性能,或改用分组/自绘序号。


六、例程 5:大数据量(虚拟化)与搜索过滤

<!-- 万级数据必备三件套;ListBox 默认就是 VirtualizingStackPanel -->
<ListBox ItemsSource="{Binding BigList}"
         VirtualizingPanel.IsVirtualizing="True"
         VirtualizingPanel.VirtualizationMode="Recycling"
         ScrollViewer.CanContentScroll="True"/>   <!-- 必须为 True,否则虚拟化失效 -->
// 搜索/过滤:不要去重建集合,用视图的 Filter(增删改仍会同步)
private void TxtKeyword_TextChanged(object sender, TextChangedEventArgs e)
{
    var view = CollectionViewSource.GetDefaultView(vm.BigList);
    var kw = txtKeyword.Text.Trim();

    view.Filter = o => string.IsNullOrEmpty(kw)
                    || ((Employee)o).Name.Contains(kw, StringComparison.OrdinalIgnoreCase);
}

性能红线:

  • 只在"大道具"场景不要用 WrapPanel 替换 ItemsPanel——WrapPanel 不支持虚拟化,10000 项会直接卡死。
  • ItemTemplate 里别塞 WebBrowser、大图、复杂嵌套控件;模板会被反复实例化。
  • 需要定位某一行容器时,ItemContainerGenerator.ContainerFromItem 对未实现化的项返回 null,先 ScrollIntoView(item) 再取。

七、常见坑清单(按出现频率排序)

  1. ItemsSource 与 Items 混用:XAML 里写了几个 <ListBoxItem> 又设 ItemsSource,运行时抛"Items collection must be empty before using ItemsSource"。内联项要清空后才能绑数据。
  2. SelectedItem 类型想当然:数据是 string 就拿到 string,数据是 Employee 就拿到 Employee,两者不能强转。
  3. 用 List<T> 做数据源:增删项界面不刷新 → 换 ObservableCollection<T>。
  4. 项内属性改了界面不动:模型缺 INotifyPropertyChanged。
  5. SelectedItems 无法绑定:它是 IList 而非依赖属性;多选 MVVM 需附加属性,或改用带 CheckBox 的 ItemTemplate 自管理勾选状态。
  6. SelectedIndex 与顺序强耦合:排序或过滤后指向别的项,优先用 SelectedItem / SelectedValue。
  7. 数据没加载就设 SelectedIndex = 0:无效,需在 ItemsSource 赋值之后或 Loaded 事件里设。
  8. SelectionChanged 里改选中项导致递归:必须加 _updating 标志位。
  9. ItemsSource 置 null 会清空选中:绑定的 ViewModel 属性被双向绑定写回 null,此时别在 setter 里做重活。
  10. Multiple 模式下 SelectedItem 只返回首个选中项,读全集请用 SelectedItems。
  11. 想要"只看不选":WPF 没有 SelectionMode="None",正确做法是直接用 ItemsControl(同一套 ItemTemplate 语法,零成本迁移)。
  12. ListBoxItem 双击/右键:ListBoxItem 不暴露双击事件,需在 ListBox 上挂 MouseDoubleClick 并结合 SelectedItem 判断。

八、选型对比

1.几个常用类似控件的对比

控件适用场景关键差异
ListBox列表选择、可按项滚动、支持虚拟化单选/多选,默认项级滚动
ListView需要列头、多列对齐的只读表格(GridView)默认像素级滚动,列宽需手动设
DataGrid需要编辑单元格、排序、列宽拖拽功能全但重,绑定模型更复杂
ComboBox空间紧张、选择后收起展开部分本质就是一个 ListBox
ItemsControl纯展示、不可选(如卡片流)无选中概念,最轻量

一句话选型:只需"选一项/多项"用 ListBox;需要列对齐看表格用 ListView;需要编辑进 DataGrid;只是摆放内容用 ItemsControl。

如果需要,我可以把这套例程整理成一个可直接编译的 .NET WPF 示例工程(含 MVVM 多选绑定与虚拟化压测页),说一声即可。

2.ListBox与ListView的区别、使用场景与选用

ListView 就是 ListBox 的子类(ListView : ListBox,容器 ListViewItem : ListBoxItem)。所以 ItemsSource、ItemTemplate、ItemContainerStyle、SelectionMode、SelectedItems、虚拟化这些全部通用 —— 两者的真正差别只有一条:ListView 多了一个 View 属性,可以把一维列表 “投影” 成多列表格,内置的投影器只有 GridView。

2.1 核心差异对照
维度ListBoxListView
本质一维可选列表ListBox + View(默认 GridView)
容器类型ListBoxItemListViewItem(样式 TargetType 必须写对它)
列头无有,GridViewColumn.Header
多列能力只能靠 ItemsPanel 换 WrapPanel/UniformGrid 做流式排列真正的列对齐 + 列宽拖拽 + 列重排
滚动单位按项滚动(CanContentScroll=True)按像素滚动(CanContentScroll=False),滚动手感更细腻
虚拟化默认开默认也开(像素滚动不影响虚拟化)
排序无内置 UI无内置 UI,要自己处理 GridViewColumnHeader.Click
编辑单元格不支持不支持(要编辑请上 DataGrid)
典型用途选择器、清单、标签墙只读报表、配置列表、列对齐的台账

一个常被问到的细节:ListView 不设 View 时,渲染效果和 ListBox 几乎一样 —— 但这没有实际价值,别为了 “看起来一样” 乱用。

2.2 怎么选:按 “用户要对这张表做什么”
  1. 只是一行一个对象、点一下选中它 → ListBox。最简单,也最快。
  2. 用户需要 “列” 这个概念(看列头、对齐比较、拖列宽、按列排序)→ ListView + GridView,且列宽给固定值。
  3. 用户要改单元格内容、要增删行、要前端排序 / 筛选 → 直接 DataGrid,别用 ListView 硬扛。
  4. 要卡片流、磁贴、标签墙、多列瀑布 → ListBox + WrapPanel,或干脆 ItemsControl(不需要选中时)。
  5. 空间紧张、选完收起 → ComboBox(下拉展开部分本质就是个 ListBox)。
  6. 纯展示不可交互 → ItemsControl,省掉 Selector 的开销。

一句话记忆:ListBox 是 “选什么”,ListView 是 “看表格顺便选一行”,DataGrid 是 “编辑一张表”。

2.3 性能与复用提醒
  • 两者默认都开虚拟化(默认 ItemsPanel 都是 VirtualizingStackPanel),万级数据都能扛;ListView 因为多了列头测量与多列布局,同样数据量下略重,但差距通常不在数量级。
  • 别为了 “优化” 把 ListView 的 ScrollViewer.CanContentScroll 改成 True:那会把它变成按项滚动,行高不一时体验明显变差,虚拟化并不会因此更快。
  • 上一轮工程里的 ListBoxSelectionBinder 可以直接挂到 ListView:它的回调判断是 d is ListBox,而 ListView 正是 ListBox 的子类,SelectionMode/SelectedItems 语义完全一致。
  • 高 DPI 下 GridView 常见 1px 缝隙,给窗口加 UseLayoutRounding="True"、SnapsToDevicePixels="True" 即可。

九、源码

零第三方依赖(不引 CommunityToolkit.Mvvm 之类的库),每个文件都能单独当教材看。

1. 目录结构

WpfListBoxDemo/
├─ WpfListBoxDemo.csproj        工程文件(WinExe + UseWPF)
├─ WpfListBoxDemo.sln           解决方案(方便 VS 打开)
├─ App.xaml / App.xaml.cs       全局样式合并 + 未处理异常写日志
├─ MainWindow.xaml              五个页签的界面(每个页签对应一组例程)
├─ MainWindow.xaml.cs           只放必须碰 UI 的代码:事件、Dispatcher 计时、ScrollIntoView
├─ Models/
│  └─ Employee.cs               数据模型(INotifyPropertyChanged 的正确写法)
├─ ViewModels/
│  └─ MainViewModel.cs          共享 ViewModel:数据、选中项、命令、压测数据生成
├─ Infrastructure/
│  ├─ ObservableObject.cs       ViewModel 基类(SetProperty + 通知)
│  ├─ RelayCommand.cs           ICommand 最简实现
│  ├─ RangeObservableCollection.cs  批量更新只通知一次 Reset
│  └─ ListBoxSelectionBinder.cs SelectedItems 双向绑定的附加属性
└─ Styles/
   └─ ListBoxStyles.xaml        自绘 ItemContainerStyle(选中高亮、斑马纹、胶囊标签)

2.五个页签分别演示什么

页签演示点建议操作
1 · 基础用法内联 ListBoxItem、Tag 挂业务主键、SelectionChanged 取 AddedItems点任意一项,看右侧结果里的 Tag 与索引
2 · 数据绑定DisplayMemberPath / ItemTemplate / SelectedValuePath、两个列表共享 Current、INotifyPropertyChanged在右侧文本框改姓名,两个列表实时刷新
3 · 多选与绑定Extended / Multiple、SelectedItems 双向绑定、VM 侧"全选/反选/清空"命令按 Ctrl 多选后点"全选",看计数与界面双向同步
4 · 外观定制自绘 ControlTemplate、AlternationCount 斑马纹、ItemsPanel 换 WrapPanel注意底部红框:换面板会关闭虚拟化
5 · 虚拟化压测虚拟化三件套、10 万条秒开、ScrollIntoView、非虚拟化对照组先点"填充 10 万条",再点"定位到第 5 万条"

3.关键实现说明

1. SelectedItems 不能直接绑定

ListBox.SelectedItems 是只读的 IList、不是依赖属性,{Binding SelectedItems} 写不出来。
ListBoxSelectionBinder 用一个附加依赖属性做双向同步:

<ListBox SelectionMode="Extended"
         ItemsSource="{Binding Employees}"
         infra:ListBoxSelectionBinder.SelectedItems="{Binding SelectedEmployees}" />
  • 界面 → ViewModel:挂 SelectionChanged,把 SelectedItems 写回集合
  • ViewModel → 界面:挂集合的 CollectionChanged,反推 SelectedItem(s)
  • 两个方向都用 IsSyncing 闸门防重入,否则一次点击会来回触发
  • 换绑时先解掉旧集合的监听:既防泄漏,也防"旧集合还能改界面"的诡异 bug
2. 工程里已经踩过并修掉的两个坑
  1. TwoWay 绑定到只读属性会炸
    附加属性默认 BindsTwoWayByDefault,而 ViewModel 里若写成 public ObservableCollection<X> Items { get; },
    WPF 会在布局阶段抛
    System.InvalidOperationException: 无法对…只读属性进行 TwoWay 或 OneWayToSource 绑定。
    → 集合属性必须带 setter(本工程用 SetProperty 实现)。

  2. Single 模式不能碰 SelectedItems
    在单选列表上调用 SelectedItems.Clear() 会抛
    只能在多选模式中更改 SelectedItems 集合。在单选模式中使用 SelectedItem。
    → binder 里对 SelectionMode.Single 分支改走 SelectedItem。

3. 批量更新用 RangeObservableCollection

原生 ObservableCollection 每 Add 一次就发一次 CollectionChanged;
"全选 1 万项"就是 1 万次界面刷新。本工程的 ReplaceAll/AddRange 改完只发一次 Reset。

4. 虚拟化的三个前提(缺一不可)
<ListBox VirtualizingPanel.IsVirtualizing="True"
         VirtualizingPanel.VirtualizationMode="Recycling"
         ScrollViewer.CanContentScroll="True" />

再加两条经验:

  • 不要自定义 ItemsPanel(WrapPanel / StackPanel / UniformGrid 都会关闭虚拟化)
  • ItemTemplate 要轻,别放图片、WebBrowser 之类的重控件
5. 计时为什么要绕 Dispatcher

FillBigList 只统计"构造集合"的时间;真正的代价在渲染。
所以 MainWindow 用 Dispatcher.BeginInvoke(..., DispatcherPriority.ApplicationIdle)
等这一帧画完再补上"首屏渲染耗时",否则数字会骗人。

4.UI 部分

MainWindow.xaml, ListBoxStyles.xaml 共2文件

//1 MainWindow.xaml
<Window x:Class="WpfListBoxDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:infra="clr-namespace:WpfListBoxDemo.Infrastructure"
        Title="WPF ListBox 详解示例" Height="800" Width="1120"
        WindowStartupLocation="CenterScreen"
        FontFamily="Microsoft YaHei UI" FontSize="13"
        Background="#F4F5F7">

    <Grid Margin="14">
        <TabControl>

            <!-- =====================================================================
                 页签 1:基础用法(内联项 + SelectionChanged,非 MVVM 的老写法)
                 ===================================================================== -->
            <TabItem Header="1 · 基础用法">
                <Grid Margin="18">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="360" />
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>

                    <StackPanel>
                        <TextBlock Text="内联 ListBoxItem + SelectionChanged" Foreground="#666" Margin="0,0,0,8" />

                        <!--
                            这里的子项是 ListBoxItem,所以事件里取到的 SelectedItem 类型就是 ListBoxItem;
                            若改成直接写字符串/业务对象,SelectedItem 的类型会跟着变——这是最常见的类型转换坑。
                        -->
                        <ListBox x:Name="LstFruit"
                                 Height="320"
                                 SelectionMode="Single"
                                 SelectionChanged="LstFruit_SelectionChanged">
                            <ListBoxItem Content="苹果" Tag="apple" />
                            <ListBoxItem Content="香蕉" Tag="banana" />
                            <ListBoxItem Content="橙子" Tag="orange" />
                            <ListBoxItem Content="西瓜" Tag="watermelon" />
                            <ListBoxItem Content="葡萄" Tag="grape" />
                            <ListBoxItem Content="芒果" Tag="mango" />
                        </ListBox>

                        <TextBlock Margin="0,10,0,0" Foreground="#999" TextWrapping="Wrap">
                            SelectionMode 默认即 Single;Multiple / Extended 见第 3 页。
                        </TextBlock>
                    </StackPanel>

                    <Border Grid.Column="1" Margin="20,0,0,0" Padding="20"
                            Background="White" CornerRadius="8">
                        <StackPanel>
                            <TextBlock Text="选中结果" FontSize="15" FontWeight="Bold" />

                            <TextBlock x:Name="TxtFruitResult"
                                       Margin="0,12,0,0" FontSize="16" Foreground="#1677FF"
                                       Text="(尚未选择)" />

                            <TextBlock Margin="0,22,0,0" TextWrapping="Wrap" Foreground="#888" LineHeight="22">
                                要点一:直接写子项时,WPF 会自动为每个对象生成 ListBoxItem 容器,
                                所以 SelectedItem 拿到的是 ListBoxItem,要取文本用它的 Content。
                                <LineBreak /><LineBreak />
                                要点二:Tag 是给业务主键留的位置(如苹果=apple),
                                比"用显示文本反查 ID"可靠得多。
                                <LineBreak /><LineBreak />
                                要点三:SelectionChangedEventArgs 的 AddedItems / RemovedItems 只包含
                                "本次变化"的项;要拿全部选中项请用 SelectedItems。
                            </TextBlock>
                        </StackPanel>
                    </Border>
                </Grid>
            </TabItem>

            <!-- =====================================================================
                 页签 2:数据绑定(DisplayMemberPath / ItemTemplate / SelectedValuePath)
                 ===================================================================== -->
            <TabItem Header="2 · 数据绑定">
                <Grid Margin="18">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="300" />
                        <ColumnDefinition Width="320" />
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>

                    <StackPanel>
                        <TextBlock Text="A · DisplayMemberPath(最省事)" Foreground="#666" Margin="0,0,0,8" />

                        <!-- 只显示一个字段;没法调样式、没法多字段 -->
                        <ListBox Height="390"
                                 ItemsSource="{Binding Employees}"
                                 DisplayMemberPath="Name"
                                 SelectedItem="{Binding Current}" />

                        <TextBlock Margin="0,10,0,0" Foreground="#999" TextWrapping="Wrap">
                            绑定 SelectedItem 时不需要写 Mode=TwoWay,它本身就是双向的。
                        </TextBlock>
                    </StackPanel>

                    <StackPanel Grid.Column="1" Margin="18,0,0,0">
                        <TextBlock Text="B · ItemTemplate(多字段 / 图标)" Foreground="#666" Margin="0,0,0,8" />

                        <ListBox Height="390"
                                 ItemsSource="{Binding Employees}"
                                 SelectedItem="{Binding Current}"
                                 HorizontalContentAlignment="Stretch">
                            <ListBox.ItemTemplate>
                                <DataTemplate>
                                    <Grid>
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="Auto" />
                                            <ColumnDefinition Width="*" />
                                            <ColumnDefinition Width="Auto" />
                                        </Grid.ColumnDefinitions>

                                        <!--
                                            在岗/离岗小圆点:DataTrigger 根据 OnDuty 切换 Fill,
                                            这就是"绑定 + 触发器"最常见的组合用法。
                                        -->
                                        <Ellipse Grid.Column="0" Width="8" Height="8"
                                                 Margin="0,0,9,0" VerticalAlignment="Center">
                                            <Ellipse.Style>
                                                <Style TargetType="Ellipse">
                                                    <Setter Property="Fill" Value="#52C41A" />
                                                    <Style.Triggers>
                                                        <DataTrigger Binding="{Binding OnDuty}" Value="False">
                                                            <Setter Property="Fill" Value="#BFBFBF" />
                                                        </DataTrigger>
                                                    </Style.Triggers>
                                                </Style>
                                            </Ellipse.Style>
                                        </Ellipse>

                                        <StackPanel Grid.Column="1">
                                            <TextBlock Text="{Binding Name}" FontWeight="SemiBold" />
                                            <TextBlock Text="{Binding Dept}" Foreground="#999" FontSize="11" />
                                        </StackPanel>

                                        <!-- 只读展示,用 OneWay 明确意图 -->
                                        <TextBlock Grid.Column="2" FontSize="11" Foreground="#999"
                                                   VerticalAlignment="Center"
                                                   Text="{Binding Title, Mode=OneWay}" />
                                    </Grid>
                                </DataTemplate>
                            </ListBox.ItemTemplate>
                        </ListBox>

                        <TextBlock Margin="0,10,0,0" Foreground="#999" TextWrapping="Wrap">
                            左右两个列表绑的是同一个 Current,任选其一,另一边会同步选中。
                        </TextBlock>
                    </StackPanel>

                    <Border Grid.Column="2" Margin="20,0,0,0" Padding="20"
                            Background="White" CornerRadius="8">
                        <StackPanel>
                            <TextBlock Text="当前选中项(ViewModel.Current)" FontSize="15" FontWeight="Bold" />

                            <TextBlock Margin="0,12,0,0">
                                <Run Text="工号:" Foreground="#999" /><Run Text="{Binding Current.Id, Mode=OneWay}" />
                            </TextBlock>
                            <TextBlock Margin="0,4,0,0">
                                <Run Text="部门:" Foreground="#999" /><Run Text="{Binding Current.Dept, Mode=OneWay}" />
                            </TextBlock>
                            <TextBlock Margin="0,4,0,0">
                                <Run Text="岗位:" Foreground="#999" /><Run Text="{Binding Current.Title, Mode=OneWay}" />
                            </TextBlock>

                            <TextBlock Margin="0,18,0,6" Foreground="#888" TextWrapping="Wrap">
                                下面直接改姓名:输入即生效,两个列表会实时刷新。
                                靠的是模型里的 INotifyPropertyChanged,不是靠重设 ItemsSource。
                            </TextBlock>
                            <TextBox Padding="7,6"
                                     Text="{Binding Current.Name, UpdateSourceTrigger=PropertyChanged}" />

                            <Separator Margin="0,20" BorderBrush="Red" BorderThickness="6" />

                            <TextBlock Text="SelectedValuePath:只取Id,不取整个对象" Foreground="#666" TextWrapping="Wrap" />
                            <ListBox Margin="0,8,0,0" Height="130"
                                     ItemsSource="{Binding Employees}"
                                     DisplayMemberPath="Name"
                                     SelectedValuePath="Id"
                                     SelectedValue="{Binding SelectedId}" />
                            <TextBlock Margin="0,6,0,0">
                                <Run Text="SelectedId = " Foreground="#999" />
                                <Run Text="{Binding SelectedId, Mode=OneWay}" Foreground="#1677FF" />
                            </TextBlock>
                        </StackPanel>
                    </Border>
                </Grid>
            </TabItem>

            <!-- =====================================================================
                 页签 3:多选(Extended / Multiple + SelectedItems 双向绑定)
                 ===================================================================== -->
            <TabItem Header="3 · 多选与 SelectedItems 绑定">
                <Grid Margin="18">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>

                    <StackPanel>
                        <TextBlock Text="Extended:Ctrl 加选 / Shift 连选,单击会清空重来" Foreground="#666" Margin="0,0,0,8"/>

                        <!--
                            核心:SelectedItems 是只读 IList、不是依赖属性,{Binding SelectedItems} 写不出来,
                            所以用附加属性 infra:ListBoxSelectionBinder.SelectedItems 做双向同步。
                        -->
                        <ListBox Height="340"
                                 SelectionMode="Extended"
                                 ItemsSource="{Binding Employees}"
                                 DisplayMemberPath="Name"
                                 ItemContainerStyle="{StaticResource CleanItemStyle}"
                                 infra:ListBoxSelectionBinder.SelectedItems="{Binding SelectedEmployees}" />

                        <StackPanel Orientation="Horizontal" Margin="0,12,0,0">
                            <Button Content="全选" Command="{Binding SelectAllCommand}"
                                    Padding="14,5" Margin="0,0,8,0" MinWidth="72" />
                            <Button Content="反选" Command="{Binding InvertSelectionCommand}"
                                    Padding="14,5" Margin="0,0,8,0" MinWidth="72" />
                            <Button Content="清空已选" Command="{Binding ClearSelectionCommand}"
                                    Padding="14,5" MinWidth="72" />
                        </StackPanel>

                        <TextBlock Margin="0,12,0,0">
                            <Run Text="ViewModel 侧:" Foreground="#999" />
                            <Run Text="{Binding SelectedEmployees.Count, Mode=OneWay}" FontWeight="Bold" 				                                   Foreground="#1677FF" />
                            <Run Text=" 项" Foreground="#999" />
                        </TextBlock>

                        <!-- 把 VM 集合直接摊开显示,用来证明"界面点选 → VM 同步"确实生效 -->
                        <ItemsControl Margin="0,8,0,0" ItemsSource="{Binding SelectedEmployees}">
                            <ItemsControl.ItemTemplate>
                                <DataTemplate>
                                    <TextBlock Text="{Binding Name}" Foreground="#666" Margin="0,2" />
                                </DataTemplate>
                            </ItemsControl.ItemTemplate>
                        </ItemsControl>
                    </StackPanel>

                    <StackPanel Grid.Column="1" Margin="20,0,0,0">
                        <TextBlock Text="Multiple:点一下就是切换,不需要按 Ctrl" Foreground="#666" Margin="0,0,0,8" />

                        <ListBox Height="200"
                                 SelectionMode="Multiple"
                                 ItemsSource="{Binding Employees}"
                                 DisplayMemberPath="Name"
                                 ItemContainerStyle="{StaticResource CleanItemStyle}"
                                 infra:ListBoxSelectionBinder.SelectedItems="{Binding MultiSelected}" />

                        <TextBlock Margin="0,12,0,0">
                            <Run Text="已选 " Foreground="#999" />
                            <Run Text="{Binding MultiSelected.Count, Mode=OneWay}" FontWeight="Bold" Foreground="#1677FF"/>
                            <Run Text=" 项(两个列表各自独立同步)" Foreground="#999" />
                        </TextBlock>

                        <Border Margin="0,14,0,0" Padding="14" Background="#FFF9E6" CornerRadius="6">
                            <TextBlock TextWrapping="Wrap" Foreground="#8C6D1F" LineHeight="21">
                                注意:SelectedItems 不能直接绑定;Multiple 模式下 SelectedItem 只返回
                                索引最小的那个选中项,要全集请用 SelectedItems。
                                另外,若在 SelectionChanged 里又去改选中项,需要加防重入标志位
                                (本工程的 binder 已内置 IsSyncing 闸门)。
                            </TextBlock>
                        </Border>
                    </StackPanel>
                </Grid>
            </TabItem>

            <!-- =====================================================================
                 页签 4:外观定制(斑马纹 / 自绘模板 / WrapPanel 流式布局)
                 ===================================================================== -->
            <TabItem Header="4 · 外观定制">
                <Grid Margin="18">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="300" />
                        <ColumnDefinition Width="300" />
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>

                    <StackPanel>
                        <TextBlock Text="斑马纹:AlternationCount=2 + AlternationIndex 触发器" Foreground="#666"
                                   TextWrapping="Wrap" Margin="0,0,0,8" />

                        <ListBox Height="360"
                                 AlternationCount="2"
                                 ItemsSource="{Binding Employees}"
                                 DisplayMemberPath="Name"
                                 ItemContainerStyle="{StaticResource AltItemStyle}" />

                        <TextBlock Margin="0,10,0,0" Foreground="#999" TextWrapping="Wrap">
                            不要手写行号做隔行变色;AlternationIndex 由 ListBox 自动维护。
                        </TextBlock>
                    </StackPanel>

                    <StackPanel Grid.Column="1" Margin="18,0,0,0">
                        <TextBlock Text="自绘模板:悬停 / 选中颜色完全可控" Foreground="#666" Margin="0,0,0,8" />

                        <ListBox Height="360"
                                 ItemsSource="{Binding Employees}"
                                 ItemContainerStyle="{StaticResource CleanItemStyle}">
                            <ListBox.ItemTemplate>
                                <DataTemplate>
                                    <StackPanel>
                                        <TextBlock Text="{Binding Name}" FontWeight="SemiBold" />
                                        <TextBlock Foreground="#999" FontSize="11">
                                            <Run Text="{Binding Dept, Mode=OneWay}" />
                                            <Run Text=" · " />
                                            <Run Text="{Binding Title, Mode=OneWay}" />
                                        </TextBlock>
                                    </StackPanel>
                                </DataTemplate>
                            </ListBox.ItemTemplate>
                        </ListBox>
                    </StackPanel>

                    <StackPanel Grid.Column="2" Margin="20,0,0,0">
                        <TextBlock Text="ItemsPanel 换 WrapPanel:横向流式排列" Foreground="#666" Margin="0,0,0,8" />

                        <ListBox Height="230" Width="330" HorizontalAlignment="Left"
                                 ItemsSource="{Binding Tags}"
                                 SelectionMode="Multiple"
                                 ItemContainerStyle="{StaticResource TagItemStyle}"
                                 ScrollViewer.HorizontalScrollBarVisibility="Disabled">
                            <ListBox.ItemsPanel>
                                <ItemsPanelTemplate>
                                    <!-- 换成 WrapPanel 后虚拟化自动失效,数据量大时不要这么写 -->
                                    <WrapPanel />
                                </ItemsPanelTemplate>
                            </ListBox.ItemsPanel>
                        </ListBox>

                        <Border Margin="0,16,0,0" Padding="14" Background="#FFF1F0" CornerRadius="6">
                            <TextBlock TextWrapping="Wrap" Foreground="#A8071A" LineHeight="21">
                                红线:自定义 ItemsPanel(WrapPanel / StackPanel / UniformGrid)
                                或把 VirtualizingStackPanel 的 IsVirtualizing 关掉,
                                都会让 ListBox 一次性实例化所有条目,万级数据直接卡死。
                            </TextBlock>
                        </Border>
                    </StackPanel>
                </Grid>
            </TabItem>

            <!-- =====================================================================
                 页签 5:虚拟化压测(虚拟化 vs 非虚拟化对照)
                 ===================================================================== -->
            <TabItem Header="5 · 虚拟化压测">
                <Grid Margin="18">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>

                    <StackPanel>
                        <TextBlock Text="虚拟化开启:10 万条也能秒开、滚动流畅" Foreground="#666" Margin="0,0,0,8" />

                        <StackPanel Orientation="Horizontal">
                            <Button Content="填充 10 万条" Click="BtnFillBig_Click" Padding="14,5" Margin="0,0,8,0" />
                            <Button Content="清空" Click="BtnClearBig_Click" Padding="14,5" Margin="0,0,8,0" />
                            <Button Content="定位到第 5 万条" Click="BtnScrollBig_Click" Padding="14,5" />
                        </StackPanel>

                        <TextBlock x:Name="TxtBigStat" Margin="0,10,0,10" Foreground="#1677FF" TextWrapping="Wrap"
                                   Text="尚未填充(启动时不生成数据,避免拖慢冷启动)" />

                        <!--
                            虚拟化三件套:
                            1. IsVirtualizing=True(默认就是 True,显式写出便于理解)
                            2. VirtualizationMode=Recycling:滚动时复用容器,避免反复 new
                            3. ScrollViewer.CanContentScroll=True:按项滚动,虚拟化生效的前提
                            模板保持"轻"——只放一个 TextBlock,这正是 10 万条能秒开的关键。
                        -->
                        <ListBox x:Name="LstBig"
                                 Height="480"
                                 ItemsSource="{Binding BigList}"
                                 DisplayMemberPath="Name"
                                 ItemContainerStyle="{StaticResource CleanItemStyle}"
                                 VirtualizingPanel.IsVirtualizing="True"
                                 VirtualizingPanel.VirtualizationMode="Recycling"
                                 ScrollViewer.CanContentScroll="True" />
                    </StackPanel>

                    <StackPanel Grid.Column="1" Margin="20,0,0,0">
                        <TextBlock Text="虚拟化关闭:2 万条就明显卡顿(对照组)" Foreground="#666" Margin="0,0,0,8" />

                        <StackPanel Orientation="Horizontal">
                            <Button Content="填充 2 万条(会卡)" Click="BtnFillSlow_Click" Padding="14,5" Margin="0,0,8,0"/>
                            <Button Content="清空" Click="BtnClearSlow_Click" Padding="14,5" />
                        </StackPanel>

                        <TextBlock x:Name="TxtSlowStat" Margin="0,10,0,10" Foreground="#A8071A" TextWrapping="Wrap"
                                   Text="尚未填充(10 万条极可能让窗口假死,所以这里只放 2 万条做对照)" />

                        <ListBox x:Name="LstSlow"
                                 Height="480"
                                 ItemsSource="{Binding SlowList}"
                                 DisplayMemberPath="Name"
                                 ItemContainerStyle="{StaticResource CleanItemStyle}"
                                 VirtualizingPanel.IsVirtualizing="False"
                                 ScrollViewer.CanContentScroll="False" />

                        <TextBlock Margin="0,10,0,0" Foreground="#999" TextWrapping="Wrap">
                            对比点:填充后立刻滚动/拖动窗口,感受差异;同样 2 万条在左边列表里是顺滑的。
                        </TextBlock>
                    </StackPanel>
                </Grid>
            </TabItem>

        </TabControl>
    </Grid>
</Window>


//2 ListBoxStyles.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <!--
        1) 通用条目样式:自绘 ControlTemplate。
        为什么要自绘?系统主题会用自己的画刷绘制选中高亮,
        只改 ListBoxItem.Background 往往被盖住;自绘后颜色完全可控。
    -->
    <Style x:Key="CleanItemStyle" TargetType="ListBoxItem">
        <!-- ListBox 默认 HorizontalContentAlignment=Left,设 Stretch 才能整行铺满 -->
        <Setter Property="HorizontalContentAlignment" Value="Stretch" />
        <Setter Property="Padding" Value="10,7" />
        <Setter Property="BorderThickness" Value="0" />

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListBoxItem">
                    <!-- Background 通过 TemplateBinding 承接 ListBoxItem 自己(含斑马纹 Setter)的背景 -->
                    <Border x:Name="Bd"
                            Background="{TemplateBinding Background}"
                            CornerRadius="4"
                            Margin="1"
                            Padding="{TemplateBinding Padding}">
                        <ContentPresenter VerticalAlignment="Center" />
                    </Border>

                    <ControlTemplate.Triggers>
                        <!-- 悬停 -->
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter TargetName="Bd" Property="Background" Value="#EAF3FF" />
                        </Trigger>
                        <!-- 选中:模板触发器优先级高于 TemplateBinding,所以能盖掉斑马纹 -->
                        <Trigger Property="IsSelected" Value="True">
                            <Setter TargetName="Bd" Property="Background" Value="#1677FF" />
                            <Setter Property="Foreground" Value="White" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <!--
        2) 斑马纹样式:在 CleanItemStyle 基础上加 AlternationIndex 触发器。
        使用时必须给 ListBox 设 AlternationCount="2",否则索引恒为 0。
    -->
    <Style x:Key="AltItemStyle" TargetType="ListBoxItem" BasedOn="{StaticResource CleanItemStyle}">
        <Style.Triggers>
            <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                <Setter Property="Background" Value="#F7F8FA" />
            </Trigger>
        </Style.Triggers>
    </Style>

    <!--
        3) 标签样式:配合 WrapPanel 做多列/流式布局(胶囊形状)。
    -->
    <Style x:Key="TagItemStyle" TargetType="ListBoxItem">
        <Setter Property="Padding" Value="11,5" />
        <Setter Property="Margin" Value="3" />

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListBoxItem">
                    <Border x:Name="Bd" Background="#F0F2F5" CornerRadius="12" Padding="{TemplateBinding Padding}">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                    </Border>

                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter TargetName="Bd" Property="Background" Value="#E3F0FF" />
                        </Trigger>
                        <Trigger Property="IsSelected" Value="True">
                            <Setter TargetName="Bd" Property="Background" Value="#1677FF" />
                            <Setter Property="Foreground" Value="White" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

</ResourceDictionary>


5.Code

MainWindow.xaml.cs ,Employee.cs ,MainViewModel.cs ,ObservableObject.cs ,RelayCommand.cs ,RangeObservableCollection.cs ,ListBoxSelectionBinder.cs 共7个文件

//1. MainWindow.xaml.cs   
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using WpfListBoxDemo.ViewModels;

namespace WpfListBoxDemo
{
    /// <summary>
    /// 只处理"必须碰 UI"的事情:事件、Dispatcher 计时、ScrollIntoView。
    /// 其余逻辑都在 MainViewModel 里,便于替换成真正的 MVVM 框架。
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly MainViewModel _vm = new MainViewModel();

        public MainWindow()
        {
            InitializeComponent();
            DataContext = _vm;              // 五个页签共享同一个 ViewModel
        }

        // ---------- 页签 1:基础事件 ----------

        private void LstFruit_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender is not ListBox listBox) return;

            // 因为 XAML 里写的是 ListBoxItem,这里可以安全地按 ListBoxItem 取内容
            if (listBox.SelectedItem is ListBoxItem item)
            {
                TxtFruitResult.Text =
                    $"选中:{item.Content}(Tag = {item.Tag},SelectedIndex = {listBox.SelectedIndex})";
            }
            else
            {
                TxtFruitResult.Text = $"未选中任何项(SelectedIndex = {listBox.SelectedIndex})";
            }
        }

        // ---------- 页签 5:压测 ----------

        private void BtnFillBig_Click(object sender, RoutedEventArgs e)
        {
            long buildMs = _vm.FillBigList(100000);

            // 生成只是构造集合;真正的耗时在渲染。等这一帧画完再统计才有意义。
            var renderWatch = Stopwatch.StartNew();
            TxtBigStat.Text = $"已生成 {_vm.BigList.Count:N0} 条,构造耗时 {buildMs} ms,正在渲染…";

            Dispatcher.BeginInvoke(new Action(() =>
            {
                TxtBigStat.Text =
                    $"共 {_vm.BigList.Count:N0} 条 | 构造 {buildMs} ms | 首屏渲染 {renderWatch.ElapsedMilliseconds} ms";
            }), DispatcherPriority.ApplicationIdle);
        }

        private void BtnClearBig_Click(object sender, RoutedEventArgs e)
        {
            _vm.ClearBigList();
            TxtBigStat.Text = "已清空,可再次填充";
        }

        private void BtnScrollBig_Click(object sender, RoutedEventArgs e)
        {
            if (_vm.BigList.Count == 0)
            {
                TxtBigStat.Text = "请先点「填充 10 万条」";
                return;
            }

            // 定位到中间:虚拟化下此时只有这一屏的容器存在,
            // 目标项必须靠 ScrollIntoView 由 ItemContainerGenerator 现场生成。
            int index = _vm.BigList.Count / 2;
            var target = _vm.BigList[index];

            LstBig.ScrollIntoView(target);
            LstBig.SelectedItem = target;

            TxtBigStat.Text = $"已定位到第 {index + 1:N0} 条(该行容器此刻才被创建)";
        }

        private void BtnFillSlow_Click(object sender, RoutedEventArgs e)
        {
            long buildMs = _vm.FillSlowList(20000);

            var renderWatch = Stopwatch.StartNew();
            TxtSlowStat.Text = $"已生成 {_vm.SlowList.Count:N0} 条,构造 {buildMs} ms,正在渲染(此处会明显卡)…";

            Dispatcher.BeginInvoke(new Action(() =>
            {
                TxtSlowStat.Text =
                    $"共 {_vm.SlowList.Count:N0} 条 | 构造 {buildMs} ms | 首屏渲染 {renderWatch.ElapsedMilliseconds} ms";
            }), DispatcherPriority.ApplicationIdle);
        }

        private void BtnClearSlow_Click(object sender, RoutedEventArgs e)
        {
            _vm.ClearSlowList();
            TxtSlowStat.Text = "已清空";
        }
    }
}

//2. Employee.cs  
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace WpfListBoxDemo.Models
{
    /// <summary>
    /// 列表项模型。
    /// 只有"会变"的属性才需要 INotifyPropertyChanged;
    /// 缺了它就会出现"代码里改了 Name,ListBox 上却还是旧文本"的经典问题。
    /// </summary>
    public class Employee : INotifyPropertyChanged
    {
        // 不会被修改的字段,普通自动属性就够了,不必发通知
        public int Id { get; set; }
        public string Dept { get; set; }
        public string Title { get; set; }

        private string _name = string.Empty;

        /// <summary>姓名。会被"改名"文本框修改,所以必须发通知。</summary>
        public string Name
        {
            get => _name;
            set
            {
                if (_name == value) return;      // 值没变就不发通知,避免无谓刷新
                _name = value;
                OnPropertyChanged();             // 通知所有绑定到 Name 的 UI 重新取值
            }
        }

        private bool _onDuty = true;

        /// <summary>在岗状态。用来演示 DataTrigger 改变小圆点颜色。</summary>
        public bool OnDuty
        {
            get => _onDuty;
            set
            {
                if (_onDuty == value) return;
                _onDuty = value;
                OnPropertyChanged();
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// CallerMemberName 会自动填入调用方的属性名,
        /// 所以 setter 里不写 "Name" 也不会传错。
        /// </summary>
        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
            => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

        public override string ToString() => $"{Name}({Dept})";
    }
}


//3. MainViewModel.cs  
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Windows.Input;
using WpfListBoxDemo.Infrastructure;
using WpfListBoxDemo.Models;

namespace WpfListBoxDemo.ViewModels
{
    /// <summary>
    /// 整个窗口共用的 ViewModel:五个页签读的都是同一份数据,
    /// 这样在第 2 页改姓名,第 1/3 页如果用的是同一对象也能看到变化。
    /// </summary>
    public class MainViewModel : ObservableObject
    {
        private static readonly string[] DeptNames = { "研发部", "测试部", "产品部", "运维部", "设计部" };
        private static readonly string[] TitleNames = { "工程师", "高级工程师", "组长", "总监" };

        // ---------- 基础数据 ----------

        /// <summary>主列表数据源。用 ObservableCollection,增删项界面才会自动刷新。</summary>
        public ObservableCollection<Employee> Employees { get; } = new ObservableCollection<Employee>();

        private RangeObservableCollection<Employee> _selectedEmployees
            = new RangeObservableCollection<Employee>();

        /// <summary>
        /// Extended 模式列表的"选中集合"。
        /// RangeObservableCollection 支持批量替换,避免全选时触发 N 次界面刷新。
        ///
        /// 注意这里必须提供 setter:绑定目标是 TwoWay 的附加属性,
        /// WPF 不允许双向绑定到"只有 get"的只读属性(会抛 InvalidOperationException)。
        /// </summary>
        public RangeObservableCollection<Employee> SelectedEmployees
        {
            get => _selectedEmployees;
            set => SetProperty(ref _selectedEmployees, value);
        }

        private RangeObservableCollection<Employee> _multiSelected
            = new RangeObservableCollection<Employee>();

        /// <summary>Multiple 模式列表的选中集合。</summary>
        public RangeObservableCollection<Employee> MultiSelected
        {
            get => _multiSelected;
            set => SetProperty(ref _multiSelected, value);
        }

        /// <summary>标签流式布局演示数据。</summary>
        public ObservableCollection<string> Tags { get; } = new ObservableCollection<string>
        {
            "WPF", "ListBox", "MVVM", "数据绑定", "虚拟化",
            "ItemTemplate", "ItemContainerStyle", "附加属性", "ObservableCollection", "SelectionMode"
        };

        // ---------- 选中项 / 派生值 ----------

        private Employee _current;
        /// <summary>当前选中项。第 2 页两个列表都绑它,所以在一边选,另一边会跟着选。</summary>
        public Employee Current
        {
            get => _current;
            set => SetProperty(ref _current, value);
        }

        private int? _selectedId;
        /// <summary>配合 SelectedValuePath 演示:只关心 Id,不关心整个对象。</summary>
        public int? SelectedId
        {
            get => _selectedId;
            set => SetProperty(ref _selectedId, value);
        }

        // ---------- 大数据量演示(点击按钮才生成,避免启动就卡) ----------

        private ObservableCollection<Employee> _bigList = new ObservableCollection<Employee>();
        /// <summary>虚拟化列表的数据源(10 万条)。</summary>
        public ObservableCollection<Employee> BigList
        {
            get => _bigList;
            set => SetProperty(ref _bigList, value);
        }

        private ObservableCollection<Employee> _slowList = new ObservableCollection<Employee>();
        /// <summary>非虚拟化对照列表的数据源(2 万条)。</summary>
        public ObservableCollection<Employee> SlowList
        {
            get => _slowList;
            set => SetProperty(ref _slowList, value);
        }

        // ---------- 命令(ViewModel -> 界面 方向的验证) ----------

        public ICommand SelectAllCommand { get; }
        public ICommand InvertSelectionCommand { get; }
        public ICommand ClearSelectionCommand { get; }

        public MainViewModel()
        {
            for (int i = 1; i <= 14; i++)
                Employees.Add(CreateEmployee(i));

            // 默认选中第一项,避免详情面板一片空白、TextBox 绑定到 null 无从下手
            Current = Employees[0];
            SelectedId = Employees[0].Id;

            // 全选:一次性替换集合,binder 收到一次 Reset 就同步完界面
            SelectAllCommand = new RelayCommand(_ => SelectedEmployees.ReplaceAll(Employees));

            // 反选
            InvertSelectionCommand = new RelayCommand(_ => InvertSelection());

            // 清空
            ClearSelectionCommand = new RelayCommand(_ => SelectedEmployees.ReplaceAll(null));
        }

        private void InvertSelection()
        {
            var result = new List<Employee>();
            foreach (var employee in Employees)
            {
                if (!SelectedEmployees.Contains(employee))
                    result.Add(employee);
            }
            SelectedEmployees.ReplaceAll(result);
        }

        private static Employee CreateEmployee(int index)
        {
            return new Employee
            {
                Id = index,
                Name = $"员工 {index:D2}",
                Dept = DeptNames[index % DeptNames.Length],
                Title = TitleNames[index % TitleNames.Length],
                // 每 4 个里有一个"离岗",用来演示 DataTrigger
                OnDuty = index % 4 != 0
            };
        }

        /// <summary>
        /// 填充虚拟化列表。返回"构造数据"的耗时(毫秒);
        /// 渲染耗时需要在界面线程画完一帧后再统计,所以放在 MainWindow 里做。
        /// </summary>
        public long FillBigList(int count)
        {
            var stopwatch = Stopwatch.StartNew();

            // 关键:整体替换集合而不是循环 Add。
            // 循环 Add 会发 count 次 CollectionChanged,界面会长时间无响应。
            BigList = new ObservableCollection<Employee>(CreateItems(count));

            stopwatch.Stop();
            return stopwatch.ElapsedMilliseconds;
        }

        public long FillSlowList(int count)
        {
            var stopwatch = Stopwatch.StartNew();
            SlowList = new ObservableCollection<Employee>(CreateItems(count));
            stopwatch.Stop();
            return stopwatch.ElapsedMilliseconds;
        }

        public void ClearBigList() => BigList = new ObservableCollection<Employee>();

        public void ClearSlowList() => SlowList = new ObservableCollection<Employee>();

        /// <summary>生成 count 条演示数据(惰性枚举,不会额外占一份内存)。</summary>
        private static IEnumerable<Employee> CreateItems(int count)
        {
            for (int i = 1; i <= count; i++)
            {
                yield return new Employee
                {
                    Id = i,
                    Name = $"员工 {i:D5}",
                    Dept = DeptNames[i % DeptNames.Length],
                    Title = TitleNames[i % TitleNames.Length]
                };
            }
        }
    }
}


//4. ObservableObject.cs  
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace WpfListBoxDemo.Infrastructure
{
    /// <summary>
    /// ViewModel 基类:把"发通知"的样板代码收在一处。
    /// 示例工程不引第三方库(如 CommunityToolkit.Mvvm),保证零依赖可编译。
    /// </summary>
    public abstract class ObservableObject : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
            => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

        /// <summary>
        /// 赋值并在值真的变化时发通知;返回是否发生了变化。
        /// </summary>
        protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
        {
            if (EqualityComparer<T>.Default.Equals(field, value)) return false;
            field = value;
            OnPropertyChanged(propertyName);
            return true;
        }
    }
}


//5. RelayCommand.cs    
using System;
using System.Windows.Input;

namespace WpfListBoxDemo.Infrastructure
{
    /// <summary>
    /// 最简 ICommand 实现,供按钮绑定使用。
    /// </summary>
    public class RelayCommand : ICommand
    {
        private readonly Action<object> _execute;
        private readonly Predicate<object> _canExecute;

        public RelayCommand(Action<object> execute, Predicate<object> canExecute = null)
        {
            _execute = execute ?? throw new ArgumentNullException(nameof(execute));
            _canExecute = canExecute;
        }

        public bool CanExecute(object parameter) => _canExecute == null || _canExecute(parameter);

        public void Execute(object parameter) => _execute(parameter);

        /// <summary>
        /// 挂到 CommandManager 上,WPF 会在焦点/输入变化时自动重新询问可用状态,
        /// 省掉手写 RaiseCanExecuteChanged 的麻烦。
        /// </summary>
        public event EventHandler CanExecuteChanged
        {
            add => CommandManager.RequerySuggested += value;
            remove => CommandManager.RequerySuggested -= value;
        }
    }
}



//6. RangeObservableCollection.cs  
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;

namespace WpfListBoxDemo.Infrastructure
{
    /// <summary>
    /// 支持"批量修改"的 ObservableCollection。
    /// 原生版本每个 Add 都会发一次 CollectionChanged;
    /// 全选 1 万项就是 1 万次刷新,界面会明显卡顿。
    /// 这里改成"改完只发一次 Reset"。
    /// </summary>
    public class RangeObservableCollection<T> : ObservableCollection<T>
    {
        public RangeObservableCollection() { }

        /// <summary>一次构造完成,不会逐项发通知,适合"一次性装载大量数据"。</summary>
        public RangeObservableCollection(IEnumerable<T> items) : base(items) { }

        /// <summary>追加一批元素,只通知一次。</summary>
        public void AddRange(IEnumerable<T> items)
        {
            if (items == null) return;

            CheckReentrancy();                       // 防止在 CollectionChanged 处理中再次改动

            foreach (var item in items) Items.Add(item);

            NotifyReset();                           // 一次性通知:Count / Item[] / Reset
        }

        /// <summary>整体替换为一批新元素,只通知一次。用于"全选/反选"。</summary>
        public void ReplaceAll(IEnumerable<T> items)
        {
            CheckReentrancy();

            Items.Clear();
            if (items != null)
                foreach (var item in items) Items.Add(item);

            NotifyReset();
        }

        private void NotifyReset()
        {
            OnPropertyChanged(new PropertyChangedEventArgs(nameof(Count)));
            OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
            OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
        }
    }
}


//7. ListBoxSelectionBinder.cs
using System.Collections;
using System.Collections.Specialized;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;

namespace WpfListBoxDemo.Infrastructure
{
    /// <summary>
    /// 让 ListBox.SelectedItems 可以双向绑定。
    ///
    /// 背景:ListBox.SelectedItems 是 IList 类型的普通属性(不是依赖属性),
    /// 所以 {Binding SelectedItems} 写不出来。业界通行做法是写这个附加属性:
    /// 把 ListBox 的选中项与 ViewModel 里的集合(实现 IList)互相同步。
    ///
    /// 用法:
    ///   infra:ListBoxSelectionBinder.SelectedItems="{Binding SelectedEmployees}"
    ///
    /// 注意:ViewModel 侧的集合建议用 ObservableCollection,
    /// 这样"代码里改集合"也能立刻反映到界面上。
    /// </summary>
    public static class ListBoxSelectionBinder
    {
        public static readonly DependencyProperty SelectedItemsProperty =
            DependencyProperty.RegisterAttached(
                "SelectedItems",
                typeof(IList),
                typeof(ListBoxSelectionBinder),
                new FrameworkPropertyMetadata(
                    null,
                    FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,   // 让 {Binding} 默认双向
                    OnSelectedItemsChanged));

        public static IList GetSelectedItems(DependencyObject element)
            => (IList)element.GetValue(SelectedItemsProperty);

        public static void SetSelectedItems(DependencyObject element, IList value)
            => element.SetValue(SelectedItemsProperty, value);

        /// <summary>每个 ListBox 一份同步状态,避免用字段污染静态类。</summary>
        private sealed class SyncState
        {
            public IList Source;                       // 绑定的 ViewModel 集合
            public bool IsSyncing;                     // 防重入闸门
            public bool SelectionHooked;               // SelectionChanged 只挂一次
            public NotifyCollectionChangedEventHandler CollectionHandler;
        }

        private static readonly ConditionalWeakTable<ListBox, SyncState> States
            = new ConditionalWeakTable<ListBox, SyncState>();

        private static void OnSelectedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is not ListBox listBox) return;

            var state = States.GetValue(listBox, _ => new SyncState());

            // 1) 先摘掉旧集合的监听:否则旧集合仍会往这个 ListBox 里回写,还会造成泄漏
            if (state.Source is INotifyCollectionChanged oldCollection && state.CollectionHandler != null)
                oldCollection.CollectionChanged -= state.CollectionHandler;
            state.CollectionHandler = null;

            state.Source = e.NewValue as IList;

            // 2) SelectionChanged 只挂一次
            if (!state.SelectionHooked)
            {
                listBox.SelectionChanged += OnListBoxSelectionChanged;
                state.SelectionHooked = true;
            }

            // 3) 监听新集合:ViewModel 主动增删选中项时,界面要跟着变
            if (state.Source is INotifyCollectionChanged newCollection)
            {
                state.CollectionHandler = (sender, args) => PushSelectionToUi(listBox, state);
                newCollection.CollectionChanged += state.CollectionHandler;
            }

            // 4) 绑定刚建立时先做一次 ViewModel -> 界面 的初始化
            PushSelectionToUi(listBox, state);
        }

        /// <summary>界面 -> ViewModel:用户在列表里点选后,写回 ViewModel 集合。</summary>
        private static void OnListBoxSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender is not ListBox listBox) return;
            if (!States.TryGetValue(listBox, out var state)) return;
            if (state.Source == null || state.IsSyncing) return;

            state.IsSyncing = true;
            try
            {
                state.Source.Clear();
                foreach (var item in listBox.SelectedItems)
                    state.Source.Add(item);
            }
            finally
            {
                state.IsSyncing = false;               // 无论如何都要解锁,否则后续同步全失效
            }
        }

        /// <summary>ViewModel -> 界面:代码里改了选中集合,反推回 ListBox。</summary>
        private static void PushSelectionToUi(ListBox listBox, SyncState state)
        {
            if (state.Source == null || state.IsSyncing) return;

            state.IsSyncing = true;
            try
            {
                // 单选模式绝对不能碰 SelectedItems:Selector 会抛
                // "只能在多选模式中更改 SelectedItems 集合",必须走 SelectedItem。
                if (listBox.SelectionMode == SelectionMode.Single)
                {
                    object first = state.Source.Count > 0 ? state.Source[0] : null;
                    listBox.SelectedItem = first != null && listBox.Items.Contains(first) ? first : null;
                    return;
                }

                listBox.SelectedItems.Clear();

                foreach (var item in state.Source)
                {
                    // 数据源里没有的项直接忽略,避免 ItemsSource 已切换时抛异常
                    if (!listBox.Items.Contains(item)) continue;

                    listBox.SelectedItems.Add(item);
                }
            }
            finally
            {
                state.IsSyncing = false;
            }
        }
    }
}

十、演示界面

1 · 基础用法

页签演示点建议操作
1 · 基础用法内联 ListBoxItem、Tag 挂业务主键、SelectionChanged 取 AddedItems点任意一项,看右侧结果里的 Tag 与索引

在这里插入图片描述

2 · 数据绑定

页签建议操作演示点
2 · 数据绑定在右侧文本框改姓名,两个列表实时刷新DisplayMemberPath / ItemTemplate / SelectedValuePath、两个列表共享 Current、INotifyPropertyChanged
在这里插入图片描述

3 · 多选与绑定

页签演示点建议操作
3 · 多选与绑定Extended / Multiple、SelectedItems 双向绑定、VM 侧"全选/反选/清空"命令按 Ctrl 多选后点"全选",看计数与界面双向同步

在这里插入图片描述

4 · 外观定制

页签演示点建议操作
4 · 外观定制自绘 ControlTemplate、AlternationCount 斑马纹、ItemsPanel 换 WrapPanel注意底部红框:换面板会关闭虚拟化
在这里插入图片描述

5 · 虚拟化压测

页签演示点建议操作
5 · 虚拟化压测虚拟化三件套、10 万条秒开、ScrollIntoView、非虚拟化对照组先点"填充 10 万条",再点"定位到第 5 万条"

在这里插入图片描述

转载自 CSDN-专业IT技术社区

原文链接:https://blog.csdn.net/yunmaowu0917/article/details/171607055

文章来源转载

评论

评论列表

微信小程序
QQ小程序

关于作者

点赞数:0
关注数:0
粉丝:0
文章:0
关注标签:0
加入于:--