问题
I am fairly new to C# and try to develop Windows 10 UWP app as a hobby project.
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 grid view is bind to
public sealed partial class MainBrowser : Page
{
...
private ObservableCollection<Item> fileInCurrentFolderListUI = new ObservableCollection<Item>();
...
}
There is a list of button on the left side of the app. Each button will call a method that will return a ObservableCollection<Item> back.
The problem is I need to do something like
foreach (Item file in ReturnObservableCollection)
{
fileInCurrentFolderList.Add(item);
}
Instead of this
fileInCurrentFolderList = ReturnObservableCollection;
To able to trigger update in UI. How can I change this?
回答1:
What's happening is that ObservableCollection is reporting when items are added or removed from it, but if the collection itself changes (i.e. a new instance is instantiated) there's nothing to report the change. One solution is to use the INotifyPropertyChanged interface in your ViewModel and report changes to the properties.
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 backing field in the declaration as you've done before or just initialize the property in the constructor. Just make sure that you bind to the property and not the backing field. Additionally, if you are going to assign a new object, make sure you do it to the property, so that the change may be broadcasted. Basically, don't interact with the backing field, just do everything through the property.
来源:https://stackoverflow.com/questions/32546360/c-sharp-xaml-ui-not-update-after-change-an-instance-of-observablecollection