添加项目时可观察集合不更新

Observable Collection not updating when adding item

我已经尝试了所有方法,但我无法更新我的可观察集合并反映在 UI 中。我有一个方法可以向绑定到 CollectionViewSource 的集合添加一个新条目,而 CollectionViewSource 又绑定到我的集合。当我 运行 应用程序通用应用程序时,我正确地获得了列表,但是如果我在单击时添加一个值,则没有任何反映。有什么建议吗?

XAML 看起来像这样:

<SemanticZoom>
                <SemanticZoom.ZoomedInView>
                    <ListView IsHoldingEnabled="True"
                          ItemsSource="{Binding Mode=OneWay, Source={StaticResource MenuGroups}}" 
                          ItemTemplate="{StaticResource MenuItemTemplate}"
                          ContinuumNavigationTransitionInfo.ExitElementContainer="True">
                        <ListView.GroupStyle>
                            <GroupStyle HidesIfEmpty="True" HeaderTemplate="{StaticResource MenuGroupHeaderTemplate}"/>
                        </ListView.GroupStyle>
                    </ListView>
                </SemanticZoom.ZoomedInView>
                <SemanticZoom.ZoomedOutView>
                    <GridView Background="Black" 
                          ItemsSource="{Binding Source={StaticResource MenuGroups}, Path=CollectionGroups}"
                          ItemTemplate="{StaticResource MenuJumpTemplate}">
                    </GridView>
                </SemanticZoom.ZoomedOutView>
            </SemanticZoom>

下面是我的代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using TestWin.TestWinService;
using System.Globalization;
using System.Collections.ObjectModel;
using System.ComponentModel;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace TestWin
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MenuPage : Page
    {
        #region Members
        TestWinConnectionClient TestWinService;
        ObservableCollection<Menu> ocMenuItems = null;
        ObservableCollection<AlphaKeyGroup<Menu>> ocItemSource = null;
        #endregion Members

        #region Properties
        public ObservableCollection<Menu> MenuItems
        {
            get
            {
                if (ocMenuItems == null)
                {
                    ocMenuItems = new ObservableCollection<Menu>();

                }
                return ocMenuItems;
            }
            set
            { 
                ocMenuItems = value;           
                OnPropertyChanged("MenuItems");
            }
        }

        public ObservableCollection<AlphaKeyGroup<Menu>> ItemSource
        {
            get
            {
                if (ocItemSource == null)
                {
                    ocItemSource = new ObservableCollection<AlphaKeyGroup<Menu>>((AlphaKeyGroup<Menu>.CreateGroups(MenuItems, CultureInfo.CurrentUICulture, s => s.MenuName, true)));
                }
                return ocItemSource;
            }
            set
            {
                ocItemSource = value;
                OnPropertyChanged("ItemSource");
            }
        }
        #endregion Properties

        public MenuPage()
        {
            TestWinService = new TestWinConnectionClient();
            this.InitializeComponent();            
            #region Events
            this.Loaded += MenuPage_Loaded;
            #endregion
        }

        private void MenuPage_Loaded(object sender, RoutedEventArgs e)
        {
            SetItemSource();
        }

        private async void SetItemSource()
        {
            MenuItems = await TestWinService.GetMenuEntriesAsync();          
            ((CollectionViewSource)Resources["MenuGroups"]).Source = ItemSource;
        }

        private void TextBlock_Tapped(object sender, TappedRoutedEventArgs e)
        {
            Menu m = new Menu();
            m.MenuName = "Test Entry";
            m.SysRowID = Guid.NewGuid();
            MenuItems.Add(m);
            //this.Frame.Navigate(typeof(MenuPage));
        }

        public event PropertyChangedEventHandler PropertyChanged;
        void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

如果您将新项目添加到 MenuItems 中,您还需要刷新 CollectionViewSource 的 Source。

可能是你有一个不需要的 ObservableCollection (ItemSource),你可以看看我是如何做到的 Codeproject

并添加例如:

 private async void Test()
    {
        await Task.Delay(5000);
        for (int i = 0; i < 5; i++)
        {
            Favorites.Add(new Favorite()
            {
                Name = $"AAFriends {i}",
                Category = new Category() { Name = "Friends" },
                Uri = "http://www.expediteapps.com/blog/"
            });
        }
        InitializeGrouping();
    }

再次调用分组时才刷新