How to know when a ListBoxItem comes into view?

2019-08-17 10:23发布

问题:

Is there an event that tells me when a list box item comes into view?

The problem I have is that I can have several thousand elements that I set as my ListBox.ItemSource. Each element will generate a bitmap (which takes a while) so if I would just put this bitmap generation in the constructor creating the collection would take forever to create. Instead I want to defer the bitmap generation when an item comes into view.

Is there a way to do this? Ideally I would prefer not to loop through all the items and check if they are visible.

回答1:

Is there an event that tells me when a list box item comes into view?

You could handle the Loaded event of the ListBoxItem container:

<ListBox>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <EventSetter Event="Loaded" Handler="OnItemLoaded" />
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

private void OnItemLoaded(object sender, RoutedEventArgs e)
{
    ListBoxItem lbi = sender as ListBoxItem;
    object dataItem = lbi.DataContext;
    //...
}


回答2:

You could use SelectedItem to get the initial selection and then you could generate your bitmaps for the few above and below it - the exact number will depend on the size of your bitmaps and the size of your ListBox.

I suggest you generate a slightly larger range than you can see so when you pan up/down your list you're not constantly waiting while you render the new bitmaps; think of Google maps - if you pan a short distance the image is already there and it's only when you pan a larger distance that you have to wait for it to redraw.

As you pan up/down your list you could use IsMouseOver to find the item that you're currently hovering over and then update your rendered bitmaps accordingly, again slightly more than you can see.



标签: c# wpf listbox