介紹:
ListBox是一個基礎(chǔ)列表控件,用于展示一組數(shù)據(jù)項,它支持單項/多項選擇、數(shù)據(jù)綁定、滾動支持、自定義項模板和交互事件。ListBox繼承自ItemsControl,而ListView又繼承自ListBox,增加了View屬性。
屬性:
- ItemsSource:指定ListBox的數(shù)據(jù)源,通常是一個集合。
- DisplayMemberPath:指定綁定到ListBox的顯示屬性。
- SelectedValuePath:指定綁定到ListBox的選擇值屬性。
- SelectionMode:定義選擇模式,如單選、多選等。
- IsSynchronizedWithCurrentItem:確定ListBox是否與當(dāng)前項同步滾動。
- ItemsPanel:定義ListBox中項的布局。
- ItemContainerStyle:指定ListBox中每個項的樣式。
事件:
- SelectionChanged:當(dāng)選擇的項目發(fā)生變化時觸發(fā)。
- MouseDoubleClick:當(dāng)用戶雙擊鼠標(biāo)時觸發(fā)。
- MouseLeftButtonDown:當(dāng)用戶按下鼠標(biāo)左鍵時觸發(fā)。
基本使用:
<ListBox Width="200" Height="100">
<ListBoxItem>Item 1</ListBoxItem>
<ListBoxItem Content="Item 2"/>
<ListBoxItem>Item 3</ListBoxItem>
</ListBox>
數(shù)據(jù)綁定:
- 簡單綁定:
<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 指定的屬性名需與數(shù)據(jù)對象的屬性名完全一致
如果屬性是對象類型,可以用點語法(.)指定嵌套路徑:
假設(shè) UserTest類有一個 Address 屬性,其類型包含 City 屬性。
<ListBox DisplayMemberPath="Address.City" ... />
- 自定義數(shù)據(jù)模板
<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;
}
}
虛擬化:
你有大量數(shù)據(jù)項時,可以啟用虛擬化以提高性能,虛擬化會讓ListBox只渲染當(dāng)前可見的項,從而減少內(nèi)存占用和渲染時間。
<ListBox
VirtualizingStackPanel.IsVirtualizing="True"
VirtualizingStackPanel.VirtualizationMode="Recycling"
ScrollViewer.CanContentScroll="True"
/>
- IsVirtualizing:啟用虛擬化(默認(rèn)為 True,但部分場景需顯式設(shè)置)
- VirtualizationMode:
Standard:默認(rèn)模式,滾動時銷毀不可見項并重建新項。
Recycling:回收不可見項的容器,性能更優(yōu) - CanContentScroll:必須設(shè)置為 True,確保虛擬化與滾動條邏輯兼容