我正在尝试在ListView中虚拟化我的用户控件,如下所示:
<ListView VirtualizingStackPanel.IsVirtualizing="True"
VirtualizingStackPanel.CleanUpVirtualizedItem="stackPanel1_CleanUpVirtualizedItem"
VirtualizingStackPanel.VirtualizationMode="Standard"
Height="239" HorizontalAlignment="Left" Name="stackPanel1" VerticalAlignment="Top" Width="133" >
<ListView.Items>
<me:UserControl1 Backg="Green" />
<me:UserControl1 Backg="Blue" />
<me:UserControl1 Backg="Black" />
<me:UserControl1 Backg="Red" />
<me:UserControl1 Backg="Green" />
<me:UserControl1 Backg="Blue" />
<me:UserControl1 Backg="Black" />
<me:UserControl1 Backg="Red" />
<me:UserControl1 Backg="Blue" />
<me:UserControl1 Backg="Black" />
<me:UserControl1 Backg="Green" />
<me:UserControl1 Backg="Green" />
</ListView.Items>
</ListView>
但是,虚拟化不起作用,如果我使用Rectangle作为项目,虚拟化只是工作,如下所示:
<ListView VirtualizingStackPanel.IsVirtualizing="True"
VirtualizingStackPanel.CleanUpVirtualizedItem="stackPanel1_CleanUpVirtualizedItem"
VirtualizingStackPanel.VirtualizationMode="Standard"
Height="239" HorizontalAlignment="Left" Name="stackPanel1" VerticalAlignment="Top" Width="133" >
<ListView.Items>
<Rectangle Width="20" Height="20" Fill="Gray" ></Rectangle>
<Rectangle Width="20" Height="20" Fill="Green"></Rectangle>
<Rectangle Width="20" Height="20" Fill="Orange"></Rectangle>
<Rectangle Width="20" Height="20" Fill="Blue"></Rectangle>
<Rectangle Width="20" Height="20" Fill="Black"></Rectangle>
<Rectangle Width="20" Height="20" Fill="Red"></Rectangle>
<Rectangle Width="20" Height="20" Fill="Gray"></Rectangle>
<Rectangle Width="20" Height="20" Fill="Green"></Rectangle>
<Rectangle Width="20" Height="20" Fill="Orange"></Rectangle>
</ListView.Items>
</ListView>
UserControl1 XAML是这样的:
<UserControl x:Class="WpfApplication3.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
Width="20" Height="20"
>
<Grid>
<Rectangle Name="internalRect" Width="20" Height="20" Fill="Black"></Rectangle>
</Grid>
</UserControl>
我使用事件CleanUpVirtualizedItem来检测虚拟化是否有效,在滚动视图列表时,事件将仅使用矩形触发,而不是UserControl1,任何想法?
答案 0 :(得分:7)
你如何知道它是否适用于矩形?我真的很怀疑,矩形只是非常轻巧。如果您静态创建项目,则无法进行任何虚拟化,则始终会创建项目。您需要设置ItemsSource
并让控件创建项目,因为您可以设置包含用户控件的ItemTemplate
。