2013-10-21 49 views
0

我有一個ObservableCollection項目綁定到一個列表框作爲ItemsSource。爲ItemsSource項目創建額外的演示文稿屬性

其中一些項目也位於同一個ViewModel的另一個集合中(稱爲CollectionTwo)。

我希望能夠對Collection2中的項目進行計數並將其顯示在CollectionOne中的相應項目中。當CollectionTwo屬性更改(即Count)時,它也必須反射回CollectionOne。

我想在MVVM中做到這一點的最佳方式是將CollectionOne中的項目與一個帶有額外Count屬性的viewmodel類包裝在一起。有人能指出我的一個很好的例子嗎?或者也許另一種方法來解決這個問題,不會大大降低我的ItemsSource性能。

謝謝!

回答

1

您可以使用繼承來創建沿着這些線路自定義集合...

public class MyCollection<T> : ObservableCollection<T>, INotifyPropertyChanged 
{ 
    // implementation goes here... 
    // 
    private int _myCount; 
    public int MyCount 
    { 
     [DebuggerStepThrough] 
     get { return _myCount; } 
     [DebuggerStepThrough] 
     set 
     { 
      if (value != _myCount) 
      { 
       _myCount = value; 
       OnPropertyChanged("MyCount"); 
      } 
     } 
    } 
    #region INotifyPropertyChanged Implementation 
    public event PropertyChangedEventHandler PropertyChanged; 
    protected virtual void OnPropertyChanged(string name) 
    { 
     var handler = System.Threading.Interlocked.CompareExchange(ref PropertyChanged, null, null); 
     if (handler != null) 
     { 
      handler(this, new PropertyChangedEventArgs(name)); 
     } 
    } 
    #endregion 
} 

這是一個包裝了觀察到的集合,並提出一個自定義屬性中有一個類。該物業參與變更通知,但這取決於您的設計。

要連接起來,就可以做這樣的事情......

public MyCollection<string> Collection1 { get; set; } 
    public MyCollection<string> Collection2 { get; set; } 
    public void Initialise() 
    { 
     Collection1 = new MyCollection<string> { MyCount = 0 }; 
     Collection2 = new MyCollection<string> { MyCount = 0 }; 
     Collection2.CollectionChanged += (s, a) => 
      { 
       // do something here 
      }; 
    } 

你也可以這樣做......

Collection1.PropertyChanged += // your delegate goes here 
+0

GREAT!感謝您的簡潔解決方案。夠簡單! – Rachael

+0

嗨@GarryVass,我只是剛剛實現這個新的包裝ObservableCollection,但我不認爲它* *完全*回答我的問題。這不是在MyCount屬性中追加集合中的每個項目,對嗎?相反,它將*一個* MyCount屬性添加到整個Collection1或Collection2中?因此,爲集合中的每個項目添加附加屬性的唯一方法是定義一個附加類來包裝項目的屬性,添加一個額外的「視圖狀態」屬性,然後將其包含在常規的ObservableCollection中? – Rachael

+0

是的,如果您需要爲集合中的每個項目附加附加屬性。儘管如此,上面的框架應該會有所幫助,並且讓我知道您是否需要更新 –