Reputation: 198
I've got an ListBox
that has an DataTemplate
. This DataTemplate
is filled in CodeBehind but the performance is really bad. The method that fills it is called in the constructor. Please tell me how I can improve it
<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>
And now how I fill it:
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))
I fill 4 ListBoxes with about 100-200 items each
Upvotes: 3
Views: 1328
Reputation: 25201
Here are the problems I see:
ScrollViewer.CanContentScroll="False"
disables virtualization regardless of other properties you set. Changing it to True
should fix this.VirtualizingStackPanel
in your ItemTemplate
. The virtualization won't come into play since you have only 4 TextBlocks in each panel, and you're just adding a needless overhead. Use StackPanel
instead.Upvotes: 4