locked
Listview resetting selected bound selected item when datacontext is nulled out RRS feed

  • Question

  • I have a problem when using a Listview on a page with a two way binding for the selected item. The Listview works fine until I clean up the page during the NavigatedFrom event. During the event, I null out any private fields used on the page and null out the DataContext.

    After nulling the DataContext, the Listview will set its selected item back to null,  which is not the desired behavior.

    The only reason I null out the DataContext on the page is because, without doing so, the page never seems to get garbage collected. 

    None of the other controls seem to do this. The bound text in a text box does not get reset, nor does a Boolean bound checkbox IsChecked property.

    The app is written in C# and Xaml.

    Any help is much appreciated!

    Thanks,
    Sean

    Thursday, February 27, 2014 1:58 PM

All replies

  • This makes sense. The ListView doesn't have any entries to display after you remove the binding. Typically you'dleave the binding until the ListView was no longer shown.

    The non-collection controls you mention have a much simpler association with their bound data.

    --Rob

    Thursday, February 27, 2014 4:25 PM
    Moderator
  • Anyone have a possible solution to this?
    Monday, March 3, 2014 4:12 PM
  • A possible solution to what? What is the scenario you are trying to achieve?

    Typically you'd leave the binding until the ListView was no longer shown. If you need to persist the selection while the data binding is removed and reset then you'd have to capture the selection before removing the data binding and then reset it after resetting the data binding.

    --Rob

    Monday, March 3, 2014 11:52 PM
    Moderator
  • I am removing the data context from the page during the Navigated From event (also tried Unloaded).  As far as I know, that is the last possible time to interact with the page. 

    The control is no longer showing when I remove the data context.  When the data context is removed, the listview resets its selected item to NULL.  This is what I'm trying to avoid.

    Without clearing the data context, the page never seems to get freed from memory, causing the app's memory footprint to grow and grow.

    My Navigate from code looks something like this:

            protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
            {
                _viewModel = null;
                DataContext = null;
    
                base.OnNavigatingFrom(e);
            }

    Thanks,
    Sean

    Tuesday, March 4, 2014 1:47 PM