views:

623

answers:

2

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.

A: 

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;
}
M. Jahedbozorgan
I don't know if that works out for me, because I would need this check on every scrolling activity and on every single size changed event (per mouse move event, and that's pretty often).I think that would slow down the performance at least as leaving all items visible and not collapsed.
dalind
Why don't you filter contents of your listbox by some criteria? (e.g. by first letter of each item)
M. Jahedbozorgan
I do filter it, but in my point of view this has nothing to do with the visibility. The visibility of an item can change by every move of the track of the scrollviewer, so filtering would make no sense, I think. Or did I missunderstand something?
dalind
A: 

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.

dalind