我有一個對象模型是這樣的:數據綁定(WPF/Silverlight樣式)到集合中集合的屬性聚合的最佳方法?
class Car
{
public string Manufacturer;
public int Mileage;
public ObservableCollection<Part> Parts;
}
class Part
{
public string Name;
public int Price;
}
我想顯示「所有我的車」的總價格給用戶。我想用DataBinding(WPF/Silverlight/XAML)完成這個任務。這裏的代碼排序我想寫:
class MyWindow : Window
{
public MyWindow()
{
ObservableCollection<Car> myCars = CreateCars(); // Create a collection of cars
// Let the user edit the collection of Cars
this.DataGrid.DataContext = myCars;
// Bind to the grand total Price of all Parts in each Car.
// Should update text automatically if...
// 1) The Price of an individual Part changes
// 2) A Part is added or removed from a Car
// 3) A Car is added or removed from myCars collection
this.TotalPriceOfMyCarsLabel.Text = ??? // How?
}
}
的MVVM的做法似乎是分類模式,將是有用這裏,但我想不出來實現它的最好辦法。我的對象模型可以被修改,例如,添加INotifyPropertyChanged等。
我試圖寫的代碼本着ObservableCollection that also monitors changes on the elements in collection的精神,但代碼變得相當長,所有OnCollectionChanged和OnPropertyChanged事件處理程序都在各處飛行。
我真的想用DataBinding來處理總價格的計算和顯示,我該如何以一種乾淨的方式來做到這一點?
謝謝!
-Mike