2009-04-30 17 views
8

我有一個視圖,顯示綁定到GETALL()列表框:)如何獲得一個ItemsSource刷新其綁定?

<DockPanel> 
    <ListBox ItemsSource="{Binding GetAll}" 
      ItemTemplate="{StaticResource allCustomersDataTemplate}" 
      Style="{StaticResource allCustomersListBox}"> 
    </ListBox> 
</DockPanel> 

GETALL(被一個ObservableCollection財產在我的視圖模型:

public ObservableCollection<Customer> GetAll 
{ 
    get 
    { 
     return Customer.GetAll(); 
    } 
} 

這反過來調用GETALL()模型方法讀取XML文件以填充的ObservableCollection:

public static ObservableCollection<Customer> GetAll() 
{ 
    ObservableCollection<Customer> customers = new ObservableCollection<Customer>(); 

    XDocument xmlDoc = XDocument.Load(Customer.GetXmlFilePathAndFileName()); 
    var customerObjects = from customer in xmlDoc.Descendants("customer") 
          select new Customer 
          { 
           Id = (int)customer.Element("id"), 
           FirstName = customer.Element("firstName").Value, 
           LastName = customer.Element("lastName").Value, 
           Age = (int)customer.Element("age") 
          }; 
    foreach (var customerObject in customerObjects) 
    { 
     Customer customer = new Customer(); 

     customer.Id = customerObject.Id; 
     customer.FirstName = customerObject.FirstName; 
     customer.LastName = customerObject.LastName; 
     customer.Age = customerObject.Age; 

     customers.Add(customer); 
    } 

    return customers; 
} 

這一切工作正常,當用戶進入到另一種觀點認爲EXCEPT,編輯XML文件,回來這一觀點,其中舊數據仍呈現

我怎樣才能知道這個觀點「刷新其綁定」,使其顯示實際數據。

感覺就像我在這裏用WPF過多的HTML/HTTP隱喻一樣,我覺得有一種更自然的方式來獲取ObservableCollection來更新自己,因此它的名字,但這是我唯一的方法可以讓用戶能夠在此刻編輯WPF應用程序中的數據。所以在這裏,任何級別的幫助都會被讚賞

回答

12

一種ItemsControl請求其結合一次,之後緩存的參考。

如果集合對象的內容被修改,並且它實現了INotifyCollectionChanged(如ObservableCollection那樣),它將拾取任何添加或刪除的對象。

現在,如果你希望綁定提供一個新的集合對象的ListBox,你可以有你的視圖模型實現INotifyPropertyChanged,提高PropertyChanged,在GetAll傳遞作爲屬性名稱。 這將有警告綁定的屬性值改變的影響(有一個新的ObservableCollection隨時可以拿起),它將提供給ListBox,這將重新生成的項目。

所以只要你實現從您的應用程序的變化,由GetAll返回ObservableCollection工作,你可以添加和刪除的名單將保持同步。當你想要選擇外部修改(你可能在某處有一個刷新按鈕,或者重新加載整個文件有意義的自然點),你可以讓你的視圖模型引發PropertyChanged事件,該事件會自動調用屬性getter,它將調用靜態方法,這將返回一個新的新集合。

都捨不得虧的注意:爲什麼你給方法名屬性?

+0

我改變GETALL()來GETALL,謝謝。問題是我有兩個視圖,它們分別從各自的ViewModel中獲取單獨的GetAll ObservableCollection,當一個ObservableCollection發生更改時,另一個不會更改。我需要將這些地點存儲在全球嗎? – 2009-04-30 13:21:04

0

請您ObservableCollection參考和XML文件的最後修改時間爲您加載它的時間。每當窗口獲得焦點時,檢查磁盤文件上的時間戳。如果更改,請清除並重新填充ObservableCollection。 GUI將自動偵聽來自ObservableCollection的更改事件,並在您修改收藏夾內容時自動重新填充。

7

下面的老本行一樣,當我們刪除在集合添加對象:

CollectionViewSource.GetDefaultView(CustomObservableCollection).Refresh();