Lifecycle for ListViewItems

235 views Asked by At

By default a WPF ListView (with a GridView) is virtualized. So I bind my ItemSource property to an observable collection in a ViewModel as I am using a MVVM pattern (with Caliburn.Micro but I guess that does not matter).

How can I have a method invoke on my item view models (the items of the itemsource) when they are used (in scope and represented by a UI listviewitem) by the ListView and when they are unused (no longer in scope and represented on the UI)?

It would be very nice to lazy load some detail data but only for visible records.

1

There are 1 answers

1
Clemens On BEST ANSWER

You could have a derived ListView with overridden PrepareContainerForItemOverride and ClearContainerForItemOverride methods:

public class MyListView : ListView
{
    protected override void PrepareContainerForItemOverride(
        DependencyObject element, object item)
    {
        base.PrepareContainerForItemOverride(element, item);

        ((MyItem)item).DoSomethingOnPrepare();
    }

    protected override void ClearContainerForItemOverride(
        DependencyObject element, object item)
    {
        ((MyItem)item).DoSomethingOnClear();

        base.ClearContainerForItemOverride(element, item);
    }
}