C # XAML: user interface not updating after changing instance of ObservableCollection

I am new to C # and trying to develop a Windows 10 UWP application as a project hobby.

Part of 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> 

This kind of grid is tied to

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

On the left side of the application there is a list of buttons. Each button will call a method that returns an ObservableCollection<Item> .

The problem is that I need to do something like

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

Instead of this

 fileInCurrentFolderList = ReturnObservableCollection; 

Ability to run updates in the user interface. How can i change this?

+6
source share
1 answer

What happens when an ObservableCollection reports when items are added or removed from it, but if the collection itself changes (i.e. an instance of a new instance is created), nothing is reported about this change. One solution is to use the INotifyPropertyChanged interface in the ViewModel and report property changes.

 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)); } } } 

You can initialize the support field in the declaration, as you did before, or simply initialize the property in the constructor. Just make sure you are attached to the property, not the support area. Also, if you intend to assign a new object, be sure to do this with this property so that the change can be submitted. In principle, do not interact with the support field, just do everything through the property.

+7
source

All Articles