Search code examples
windows-phone-7xamldata-bindingsilverlight-toolkit

Stale Items Collection in ListPicker during Binding Update


I am having an issue with two-way binding the SelectedItem of the ListPicker

In my View XAML i have this ListPicker:

<toolkit:ListPicker ItemsSource="{Binding AvailableTGs}" 
                    SelectedItem="{Binding SelectedTG, Mode=TwoWay}"/>

And on my ViewModel:

public IList<Term> AvailableTGs
{
    get
    {
        return _AvailableTGs;
    }
}

private Term _SelectedTG = null;
public Term SelectedTG
{
    get
    {
        return _SelectedTG;
    }
    set
    {             
        this.RaiseAndSetIfChanged(x => x.SelectedTaxGroup, ref _SelectedTG , value);
    }
}

The First time, i set the AvailableTGs, the Binding is updated as expected. The ListPicker selects the first Item and it is pushed back into SelectedTG. The Problem is that when I then later update AvailableTGs this happens:

  • The Items are updated on the ListPicker
  • The SelectedItem obviously is not part of the new List any more, so the ListPicker selects the first item of the new List and sets it as the SelectedItem
    (at this Point, the Items of the Picker already contains the new List)
  • This new SelectedItem is pushed to the ViewModel into SelectedTG
  • There, a PropertyChanged Notification is raised
  • This causes the SelectedItem on the Picker to update again
  • When setting the SelectedItem the Picker validates that it is indeed part of the current Items collection.
  • This validation fails, because at this point, the Items collection is pointing to the old (first) List instance again.

I have no idea, why the Items Collection would change back to an old value, after it already had the new.
The OnItemsChanged Method of ListPicker is NOT called between the time Items is pointing to the new value, and the time it has the old one again.

I would be very grateful to anyone who can point me to what I am missing.
Thanks in advance
George


Solution

  • I solved my problem. (Time, food and tea are surprisingly helpful, I find :) )

    The Issue was, that I was reusing a single ViewModel instance between visits of the same Page. Even though the previous visit was no longer on the BackStack (i navigated back and then forward to the Page again), it seems the View was still alive and bound to the ViewModel.

    What was happening was, that the ListPicker instance from the previous visit was getting the updated SelectedItem, but hadn't gotten the new ItemsSource yet. This led to an Exception.

    Maybe there is a way to work around this, but I solved it by NOT reusing my ViewModels between visits.