![](/img/trans.png)
[英]Binding multiple TextBoxes to different properties of one Object, MVVM, C#
[英]c# wrap model object containing list for MVVM binding
假設我有一個模型對象
class ModelClass
{
public List<Element> eList;
public void MethodA()
{
doSomething();
}
}
我也想在 MVVM 中使用這個對象。 然后 Viewmodel 將調用MethodA
方法來操作數據,並且eList
的元素將被更新。 有沒有辦法在不使eList
成為ObservableCollection
情況下做到這一點? 我想這樣做是為了在其他地方也使用這個ModelClass
而不會造成太多代碼污染。
如果我們比較List和ObservableCollection,那么它們都是從 IList 實現的。 那里沒有太大區別。 最大的不同是 ObservableCollection 還實現了INotifyCollectionChanged接口,它允許 WPF 綁定到它。
因此,如果您不想在模型類中使用 List 而不是 ObservableCollection ,那么您需要使用INotifyCollectionChanged實現該類:
class ModelClass:INotifyCollectionChanged
{
public List<Element> eList;// call OnCollectionChanged() when you set/add/remove...the list).
public void MethodA()
{
doSomething();
}
#region INotifyCollectionChanged Members
protected void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (CollectionChanged != null)
CollectionChanged(this, e);
}
public event NotifyCollectionChangedEventHandler CollectionChanged;
#endregion
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.