WPF ListBox虚拟化

在ListBox加载大量数据的情况下,如果不进行虚拟化,内存将逐渐增大,长时间运行后将造成卡顿
所以需要虚拟化
写法

<ListBox x:Name="listBox" VirtualizingStackPanel.VirtualizationMode="Recycling"  VirtualizingStackPanel.IsVirtualizing="True">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate >
            <VirtualizingStackPanel  Orientation="Vertical" />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>

VirtualizationMode包括RecyclingStandard

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 列表开启虚拟化的方式

示例代码

VirtualizingListBox

posted @ 2021-12-27 19:15  Lulus  阅读(1176)  评论(0编辑  收藏  举报