【问题标题】:C# XAML : UI not update after change an instance of ObservableCollectionC# XAML:更改 ObservableCollection 实例后 UI 不更新
【发布时间】:2015-09-13 04:40:25
【问题描述】:

我对 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>();
...
}

应用左侧有一个按钮列表。每个按钮都会调用一个返回ObservableCollection&lt;Item&gt;的方法。

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

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

而不是这个

fileInCurrentFolderList = ReturnObservableCollection;

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

【问题讨论】:

    标签: c# xaml uwp


    【解决方案1】:

    发生的情况是 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));
            }
        }
    }
    

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

    【讨论】:

      猜你喜欢
      • 2023-03-08
      • 2014-01-01
      • 2012-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-25
      • 2016-12-17
      相关资源
      最近更新 更多