介绍:
ListBox是一个基础列表控件,用于展示一组数据项,它支持单项/多项选择、数据绑定、滚动支持、自定义项模板和交互事件。ListBox继承自ItemsControl,而ListView又继承自ListBox,增加了View属性。
属性:
- ItemsSource:指定ListBox的数据源,通常是一个集合。
- DisplayMemberPath:指定绑定到ListBox的显示属性。
- SelectedValuePath:指定绑定到ListBox的选择值属性。
- SelectionMode:定义选择模式,如单选、多选等。
- IsSynchronizedWithCurrentItem:确定ListBox是否与当前项同步滚动。
- ItemsPanel:定义ListBox中项的布局。
- ItemContainerStyle:指定ListBox中每个项的样式。
事件:
- SelectionChanged:当选择的项目发生变化时触发。
- MouseDoubleClick:当用户双击鼠标时触发。
- MouseLeftButtonDown:当用户按下鼠标左键时触发。
基本使用:
<ListBox Width="200" Height="100">
<ListBoxItem>Item 1</ListBoxItem>
<ListBoxItem Content="Item 2"/>
<ListBoxItem>Item 3</ListBoxItem>
</ListBox>
数据绑定:
- 简单绑定:
<ListBox Name="listBox" Width="300" Height="300" Background="Gray">
</ListBox>
public partial class ListBoxWin : Window
{
public ListBoxWin()
{
InitializeComponent();
List<string> list = ["name1", "name2", "name3"];
listBox.ItemsSource = list;
}
}
- 实体类绑定:
<ListBox Name="listBox" SelectionChanged="listBox_SelectionChanged"
Width="300" Height="300" Background="Gray"
DisplayMemberPath="Name" SelectedValuePath="Age">
</ListBox>
public partial class ListBoxWin : Window
{
public ListBoxWin()
{
InitializeComponent();
List<UserTest> list = [new UserTest { Name = "name1", Age = 1 }, new UserTest { Name = "name2", Age = 2 }, new UserTest { Name = "name3", Age = 3 }];
listBox.ItemsSource = list;
}
private void listBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (sender is ListBox lbox)
{
Debug.WriteLine(lbox.SelectedValue);
UserTest? user = lbox.SelectedItem as UserTest;
Debug.WriteLine(((UserTest)lbox.SelectedItem).Age);
Debug.WriteLine(user?.Age);
}
}
}
public class UserTest()
{
public string? Name { get; set; }
public int Age { get; set; }
}
注意DisplayMemberPath 指定的属性名需与数据对象的属性名完全一致
如果属性是对象类型,可以用点语法(.)指定嵌套路径:
假设 UserTest类有一个 Address 属性,其类型包含 City 属性。
<ListBox DisplayMemberPath="Address.City" ... />
- 自定义数据模板
<ListBox Name="listBox" Width="300" Height="300" Background="Gray">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="{Binding Age}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
public partial class ListBoxWin : Window
{
public ListBoxWin()
{
InitializeComponent();
List<UserTest> list = [new UserTest { Name = "name1", Age = 1 }, new UserTest { Name = "name2", Age = 2 }, new UserTest { Name = "name3", Age = 3 }];
listBox.ItemsSource = list;
}
}
虚拟化:
你有大量数据项时,可以启用虚拟化以提高性能,虚拟化会让ListBox只渲染当前可见的项,从而减少内存占用和渲染时间。
<ListBox
VirtualizingStackPanel.IsVirtualizing="True"
VirtualizingStackPanel.VirtualizationMode="Recycling"
ScrollViewer.CanContentScroll="True"
/>
- IsVirtualizing:启用虚拟化(默认为 True,但部分场景需显式设置)
- VirtualizationMode:
Standard:默认模式,滚动时销毁不可见项并重建新项。
Recycling:回收不可见项的容器,性能更优 - CanContentScroll:必须设置为 True,确保虚拟化与滚动条逻辑兼容