简体   繁体   中英

In WPF, why doesn't a ListBox VirtualizingStackPanel work on Windows XP?

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 individual TextBox in its own VirtualizingStackPanel . ListBox is virtualizing by default though, so you shouldn't need to do anything.

MSDN:

For the ListBox, the default ItemsPanelTemplate specifies the VirtualizingStackPanel. For MenuItem, the default uses WrapPanel. For StatusBar, the default uses DockPanel.

Get rid of those extra panels and see if it starts working on XP again.

Let's pretend that ListBox didn't virtualize by default though. The correct way to make it virtualize would be like this (note, that I'm setting the ItemsPanelTemplate , not the ItemTemplate ):

<ListBox>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel IsVirtualizing="True" />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</LitBox>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM