我的ListBox
有一个DataTemplate
。 CodeBehind中填充了DataTemplate
,但性能非常糟糕。填充它的方法在构造函数中调用。请告诉我如何改进它
<ListBox ScrollViewer.HorizontalScrollBarVisibility="Visible"
ScrollViewer.CanContentScroll="False"
Name="lbCars"
VirtualizingStackPanel.IsVirtualizing="True"
VirtualizingStackPanel.VirtualizationMode="Recycling"
IsSynchronizedWithCurrentItem="True">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="MaxHeight" Value="100"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Image Height="auto" Width="125" Source="{Binding car_img_src}" Grid.Column="0" />
<VirtualizingStackPanel Margin="5, 0, 0, 0" Grid.Column="1" Orientation="Vertical" VerticalAlignment="Center">
<TextBlock Text="ID:" FontSize="12" FontWeight="Bold" Margin="0, 0, 0, 2" />
<TextBlock FontWeight="Bold" FontSize="12" Text="Name:" Margin="0, 0, 0, 2"/>
<TextBlock FontSize="12" Text="Kategorie:" FontWeight="Bold" Margin="0, 0, 0, 2"/>
<TextBlock FontSize="12" Text="Tuning:" FontWeight="Bold"/>
</VirtualizingStackPanel>
<VirtualizingStackPanel Grid.Column="2" Orientation="Vertical" VerticalAlignment="Center" Margin="5, 0, 0, 0">
<TextBlock FontSize="12" Text="{Binding car_id}" Margin="0, 0, 0, 2"/>
<TextBlock FontSize="12" Text="{Binding car_name}" Margin="0, 0, 0, 2"/>
<TextBlock FontSize="12" Text="{Binding car_group}" Margin="0, 0, 0, 2"/>
<TextBlock FontSize="12" Text="{Binding car_tuning}"/>
</VirtualizingStackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
现在我如何填写它:
public MainWindow() {
InitializeComponent();
InitializeRsc();
}
InitializeRsc:
carList.Add(new carEntry { car_id = 400, car_group = "Off Road", car_img_src = "Resources/cars/Vehicle_400.jpg", car_name = "Landstalker", car_tuning = "Transfender" });
... ((about 300-500 others))
我填充4个ListBoxes,每个约100-200项
答案 0 :(得分:4)
以下是我看到的问题:
ScrollViewer.CanContentScroll="False"
都会禁用虚拟化。将其更改为True
应解决此问题。VirtualizingStackPanel
无需使用ItemTemplate
。虚拟化不会发挥作用,因为每个面板中只有4个TextBlock,而您只是添加了不必要的开销。请改用StackPanel
。