C# XAML : UI 更改 ObservableCollection 实例后不更新

C# XAML : UI not update after change an instance of ObservableCollection

我是 C# 的新手,尝试开发 Windows 10 UWP 应用程序作为业余爱好项目。

MainBrowser.XAML的一部分

            <GridView x:Name="browserPane" ItemsSource="{x:Bind fileInCurrentFolderList,Mode=OneWay}" SelectionChanged="browserPane_SelectionChanged" Margin="0,48,0,0">
                <GridView.ItemTemplate>
                    <DataTemplate x:DataType="classes:Item">
                        <StackPanel Margin="10">
                            <Image Height="268" Width="200" Source="{x:Bind Thumbnail}" x:Phase="1" Stretch="UniformToFill"></Image>
                            <TextBlock Width="200" Text="{x:Bind Caption}" TextWrapping="Wrap" TextTrimming="CharacterEllipsis" MaxLines="2"/>
                        </StackPanel>
                    </DataTemplate>
                </GridView.ItemTemplate>
            </GridView>

此网格视图绑定到

public sealed partial class MainBrowser : Page
{
...
private ObservableCollection<Item> fileInCurrentFolderListUI = new ObservableCollection<Item>();
...
}

应用程序左侧有一个按钮列表。每个按钮都会调用一个方法,该方法将 return 返回 ObservableCollection<Item>

问题是我需要做类似

的事情
foreach (Item file in ReturnObservableCollection)
    {
    fileInCurrentFolderList.Add(item);
    }

而不是这个

fileInCurrentFolderList = ReturnObservableCollection;

能够在 UI 中触发更新。 我该如何更改?

发生的事情是 ObservableCollection 在向其中添加或删除项目时报告,但如果集合本身发生更改(即实例化了一个新实例),则不会报告更改。一种解决方案是在 ViewModel 中使用 INotifyPropertyChanged 界面并报告对属性的更改。

public sealed partial class MainBrowser : Page, INotifyPropertyChanged
{
    // Backing field.
    private ObservableCollection<Item> fileInCurrentFolderListUI;
    // Property.
    public ObservableCollection<Item> FileInCurrentFolderListUI
    {
        get { return fileInCurrentFolderListUI; }
        set
        {
            if (value != fileInCurrentFolderListUI)
            {
                fileInCurrentFolderListUI = value;
                // Notify of the change.
                NotifyPropertyChanged();
            }
        }
    }

    // PropertyChanged event.
    public event PropertyChangedEventHandler PropertyChanged;

    // PropertyChanged event triggering method.
    private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

您可以像以前一样在声明中初始化支持字段,或者只在构造函数中初始化 属性。只需确保您绑定到 属性 而不是支持字段。此外,如果您要分配一个新对象,请确保对 属性 进行分配,以便可以广播更改。基本上,不要与支持字段交互,只需通过 属性.

完成所有操作