2015-09-13 96 views
6

我對C#相當陌生,嘗試將Windows 10 UWP應用程序開發爲業餘愛好項目。 MainBrowser.XAMLC#XAML:更改ObservableCollection實例後UI未更新

  <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<Item>的方法。

的問題是我需要做的是這樣

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

取而代之的是

fileInCurrentFolderList = ReturnObservableCollection; 

爲了能夠在UI觸發更新。 我該如何改變這一點?

回答

7

發生了什麼是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)); 
     } 
    } 
} 

您可以像以前那樣初始化聲明中的後臺字段,或者只是初始化構造函數中的屬性。只要確保你綁定到屬性而不是後臺字段。另外,如果您要分配一個新對象,請確保您對該屬性執行此操作,以便可以播放該更改。基本上,不要與支持領域互動,只是通過屬性做所有事情。

+2

謝謝!現在,它的工作原理應該如此。 – Suttisak

+1

@Suttisak不客氣。 –

+1

@ B.K。非常棒的使用CallerMemberName。我一直都在傳遞會員名稱的價值,這使得它更加優雅!謝謝! – RAB