gpt4 book ai didi

wpf - 虚拟化 ItemsControl?

转载 作者:行者123 更新时间:2023-12-04 13:16:30 30 4
gpt4 key购买 nike

我有一个 ItemsControl包含我想虚拟化的数据列表,但是 VirtualizingStackPanel.IsVirtualizing="True"似乎不适用于 ItemsControl .

真的是这样,还是有另一种我不知道的方法?

为了测试我一直在使用以下代码块:

<ItemsControl ItemsSource="{Binding Path=AccountViews.Tables[0]}"
VirtualizingStackPanel.IsVirtualizing="True">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Initialized="TextBlock_Initialized"
Margin="5,50,5,50" Text="{Binding Path=Name}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>

如果我更改 ItemsControlListBox ,我可以看到 Initialized事件只运行了几次(巨大的利润只是让我只需要浏览几条记录),但是作为 ItemsControl每个项目都被初始化。

我试过设置 ItemsControlPanelTemplateVirtualizingStackPanel但这似乎没有帮助。

最佳答案

实际上,它不仅仅是制作 ItemsPanelTemplate。使用 VirtualizingStackPanel .默认 ControlTemplate对于 ItemsControl没有 ScrollViewer ,这是虚拟化的关键。添加到 ItemsControl 的默认控制模板(使用 ListBox 的控制模板作为模板)为我们提供了以下信息:

<ItemsControl ItemsSource="{Binding AccountViews.Tables[0]}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Initialized="TextBlock_Initialized"
Text="{Binding Name}" />
</DataTemplate>
</ItemsControl.ItemTemplate>

<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel IsVirtualizing="True"
VirtualizationMode="Recycling" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>

<ItemsControl.Template>
<ControlTemplate TargetType="ItemsControl">
<Border BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}">
<ScrollViewer CanContentScroll="True"
Padding="{TemplateBinding Padding}"
Focusable="False">
<ItemsPresenter />
</ScrollViewer>
</Border>
</ControlTemplate>
</ItemsControl.Template>
</ItemsControl>
(顺便说一句,查看默认控件模板的好工具是 Show Me The Template )
注意事项:
您必须设置 ScrollViewer.CanContentScroll="True" ,见 here为什么。
另请注意,我输入了 VirtualizingStackPanel.VirtualizationMode="Recycling" .这将减少 TextBlock_Initialized 的次数被调用,但是在屏幕上可以看到许多 TextBlock。你可以阅读更多关于 UI 虚拟化 here .
编辑:忘记说明显而易见的:作为替代解决方案,您可以替换 ItemsControlListBox :)
另外,请查看 Optimizing Performance on MSDN page并注意到 ItemsControl不在“实现性能特征的控件”表中,这就是我们需要编辑控件模板的原因。

关于wpf - 虚拟化 ItemsControl?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2783845/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com