ListBox 基础概念
ListBox 是 WPF 中常用的列表控件,用于显示一组可滚动的数据项,支持单选或多选。其核心特性包括:
- 数据绑定:通过
ItemsSource绑定集合数据(如ObservableCollection<T>)。 - 项模板:通过
ItemTemplate自定义每一项的显示样式。 - 选择模式:通过
SelectionMode控制单选(Single)或多选(Extended)。
基本用法示例
<ListBox ItemsSource="{Binding Items}" SelectionMode="Extended">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" Foreground="Blue"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Items是绑定的数据集合(需在 ViewModel 中定义)。ItemTemplate定义了如何显示每一项数据(此处用TextBlock显示Name属性)。
数据绑定与动态更新
若要实现动态数据更新(如增删项),需使用 ObservableCollection<T>:
public class ViewModel
{
public ObservableCollection<Item> Items { get; } = new ObservableCollection<Item>();
}
public class Item
{
public string Name { get; set; }
}
在 XAML 中设置 DataContext 后,ListBox 会自动响应集合变化。
自定义样式
通过 ItemContainerStyle 修改项的外观(如悬停效果):
<ListBox.Resources>
<Style TargetType="ListBoxItem">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border Background="{TemplateBinding Background}">
<ContentPresenter/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.Resources>
处理选择事件
通过 SelectionChanged 事件获取选中项:
<ListBox SelectionChanged="ListBox_SelectionChanged"/>
private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selectedItem = (sender as ListBox)?.SelectedItem as Item;
}
虚拟化提升性能
启用 VirtualizingStackPanel 优化大数据量性能:
<ListBox VirtualizingStackPanel.IsVirtualizing="True"/>
多列布局
通过 ItemsPanel 实现横向或网格布局:
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
常见问题
- 绑定失效:确保
DataContext正确设置,且集合属性实现INotifyPropertyChanged。 - 滚动问题:检查容器高度是否受限,或启用
ScrollViewer.VerticalScrollBarVisibility。
通过上述方法,可灵活实现从简单列表到复杂交互场景的需求。
1644

被折叠的 条评论
为什么被折叠?



