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

Sut*_*sak 6 c# xaml uwp

我是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>
Run Code Online (Sandbox Code Playgroud)

此网格视图绑定到

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

应用程序左侧有一个按钮列表.每个按钮都会调用一个返回的方法ObservableCollection<Item> .

问题是我需要做类似的事情

foreach (Item file in ReturnObservableCollection)
    {
    fileInCurrentFolderList.Add(item);
    }
Run Code Online (Sandbox Code Playgroud)

而不是这个

fileInCurrentFolderList = ReturnObservableCollection;
Run Code Online (Sandbox Code Playgroud)

能够在UI中触发更新.我怎么能改变这个?

B.K*_*.K. 7

发生的事情是ObservableCollection报告何时添加或删除项目,但如果集合本身发生更改(即实例化新实例),则无法报告更改.一种解决方案是使用您的INotifyPropertyChanged接口ViewModel并报告对属性的更改.

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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 谢谢!现在,它应该工作. (2认同)