How to automatically update filter and/or sort order on CollectionViewSource, when an individual item's property changes?

前端 未结 2 595
礼貌的吻别
礼貌的吻别 2021-02-14 02:24

Ok, so this question is related to Windows Phone 7/Silverlight (updated WP7 Tools, Sept 2010), specifically filtering an underlying ObservableCollection.

2条回答
  •  北恋
    北恋 (楼主)
    2021-02-14 03:06

    Don't you just hate it when that happens, not 5 minutes gone since I posted the question, and I've figured out what the problem is - and it was something quite basic. On the CollectionViewSource object, there is a View property, which has a Refresh() function. Calling this function after a property on an underlying item contained in the ObservableCollection changes, seems to have done it.

    Basically, all I had to do was change the CollectionViewSource object into a member variable, and then save it when LoadData() is called:

    private void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        if (!App.ViewModel.IsDataLoaded)
        {
            App.ViewModel.LoadData();
            m_isSelectedListView = this.Resources["IsSelectedCollectionView"] as CollectionViewSource;
            if (m_isSelectedListView != null)
            {
                m_isSelectedListView.Source = App.ViewModel.Items;
            }
        }
    }
    

    Then, call Refresh() on the view, after any of the items in the underlying ObservableCollection changes. So in MainPage.xaml.cs, just after changing the last item, add the call to refresh:

    private void ApplicationBarIconButton_Click(object sender, EventArgs e)
    {
        ItemViewModel item = App.ViewModel.Items[App.ViewModel.Items.Count - 1];
        item.IsSelected = !item.IsSelected;
        m_isSelectedListView.View.Refresh();
    }
    

    ... and the second Pivot's ListBox is updated instantly. Such a short line of code, a whole world of difference!

    In the time it took me to write up that question, there are a hundred things I could've done :-( Ah well, better late than never I guess - thought to post the answer here, if only to save someone else tearing out their hair like I did.

提交回复
热议问题