For performance reasons, I need to use virtualization on a scrolling list box.
My XAML:
<Grid>
<StackPanel>
<Button Content="Fill" Click="Button_Click" />
<ListBox ItemsSource="{Binding People}" ScrollViewer.CanContentScroll="True" VirtualizingStackPanel.IsVirtualizing="True">
<ListBox.ItemTemplate>
<DataTemplate>
<VirtualizingStackPanel>
<TextBox Text="{Binding FirstName}" />
</VirtualizingStackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>
My Code-behind:
public MainWindow()
{
InitializeComponent();
DataContext = _mainViewModel;
}
MainViewModel _mainViewModel = new MainViewModel();
private void Button_Click(object sender, RoutedEventArgs e)
{
_mainViewModel.FillPeople();
}
My ViewModel:
class MainViewModel : INotifyPropertyChanged
{
public ObservableCollection<Person> People { get; set; }
public MainViewModel()
{
People = new ObservableCollection<Person>();
}
public void FillPeople()
{
for (int i = 0; i < 100; i++)
{
var person = new Person { FirstName = "John" };
People.Add(person);
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
My Data Class:
class Person
{
public string FirstName { get; set; }
}
When I run this code on Windows 7 and Windows 10, the list fills out quickly and correctly. When I run it on POSReady 2009 SP3 (a variant of Windows XP) the list box is blank. Using a regular StackPanel fixes it, but I need virtualization. Does anyone know what to do to get this working on XP?
...that's not how you use a
VirtualizingStackPanel. You are putting each individualTextBoxin its ownVirtualizingStackPanel.ListBoxis virtualizing by default though, so you shouldn't need to do anything.Get rid of those extra panels and see if it starts working on XP again.
Let's pretend that
ListBoxdidn't virtualize by default though. The correct way to make it virtualize would be like this (note, that I'm setting theItemsPanelTemplate, not theItemTemplate):