WPF ListBox虚拟化
作者:互联网
在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 列表开启虚拟化的方式
示例代码
标签:dataContext,虚拟化,ListBox,number,timer,WPF,listBox 来源: https://www.cnblogs.com/Lulus/p/15737513.html