Question

Hy.

I have got a ListBox with a scrollviewer in it. Each item (40++ items) of the listbox contains a textblock and a small image. When I resize the window, the resizing is very laggy. If I put the textblock visibility of the items to "collapsed", the resizing is okay. My first approach was to set the visibility of each item not displayed in the scrollviewer to "collapsed", but I couldn't find an indicator when a item is visible to the user.

Does anyone have an idea to make the resizing process less laggy, maybe some other control instead of the textblock? Thank you for you help.

Was it helpful?

Solution 2

The best way to improve the performance of resizing is, to use a VirtualizingStackPanel within your ScrollContentPresenter. You can override this in the data template of for example your ListBox, or in general, you ItemsPanel.

It does NOT render items, that are not visible, in comparison to a normal StackPanel, which renders all items all the time, no matter if they are visible to the user or not.

Works quite fine for me.

OTHER TIPS

The following specifies whether the item at the given offset is visible or not:

public bool IsItemVisible(ListBox listBox, int index)
{
    if (listBox.Items.Count != 0)
    {
        VirtualizingStackPanel vsp = (VirtualizingStackPanel)VisualTreeHelper.GetParent(listBox.ItemContainerGenerator.ContainerFromIndex(0));
        int FirstVisibleItem = (int)vsp.VerticalOffset, VisibleItemCount = (int)vsp.ViewportHeight;
        return index >= FirstVisibleItem && index <= FirstVisibleItem + VisibleItemCount;
    }

    return false;
}

You can use it like this:

private void Button_Click(object sender, RoutedEventArgs e)
{
    for (int i = listbox1.Items.Count - 1; i >= 0; i--)
        if (!IsItemVisible(listbox1, i))
            ((ListBoxItem)listbox1.Items[i]).Visibility = Visibility.Collapsed;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top