-
Notifications
You must be signed in to change notification settings - Fork 22
ListBox虚拟化
L edited this page Dec 27, 2021
·
2 revisions
在ListBox加载大量数据的情况下,如果不进行虚拟化,内存将逐渐增大,长时间运行后将造成卡顿
所以需要虚拟化
写法
<ListBox x:Name="listBox" VirtualizingStackPanel.VirtualizationMode="Recycling" VirtualizingStackPanel.IsVirtualizing="True">
<ListBox.ItemsPanel>
<ItemsPanelTemplate >
<VirtualizingStackPanel Orientation="Vertical" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
VirtualizationMode
包括Recycling
和Standard
Recycling:重复利用
Standard:创建和丢弃容器
测试:定时向ListBox加入数据
Timer timer;
int number = 1;
timer=new Timer();
timer.Interval = 1;
timer.Elapsed += AddData;
listBox.ItemsSource = new ObservableCollection<string>();
timer.Start();
private void AddData(object sender, ElapsedEventArgs e)
{
listBox.Dispatcher.Invoke(() =>
{
number++;
var dataContext = listBox.ItemsSource as ObservableCollection<string>;
if (dataContext != null)
dataContext.Add(number.ToString());
if (listBox.Items.Count > 0)
{
listBox.ScrollIntoView(listBox.Items[listBox.Items.Count - 1]);
}
if (dataContext != null && dataContext.Count > 200)
{
dataContext.Clear();
}
});
}
How to use UI virtualization with redefined ListBox templates
VirtualizationMode Enum
WPF 列表开启虚拟化的方式