[英]Cannot bind an Observable Collection to an Attached Property on an UserControl
[英]Correct way to bind IEnumerable MVVM property that isn't an observable collection
說我有這個域實體:
public class Foo
{
public string Name { get; set; }
public IEnumerable<Bar> Bars { get; set; }
}
現在讓我們說我需要將Bars
屬性綁定到WPF / MVVM應用程序中的數據網格。 通知視圖Bars
屬性已更改的適當方法是什么? 我看到一些選擇:
我可以做#1,但是我不喜歡視圖的需求導致域實體發生變化。
2號似乎還可以,但有點破舊。
3號似乎效率低下。
最好的方法是什么?
編輯
為了完整起見,基於西蒙的回答,我這樣做:
public Foo SelectedFoo
{
get { return _selectedFoo; }
set
{
_selectedFoo = value;
this.NotifyPropertyChanged(() => this.Foo);
_bars = new ObservableCollection<Bar>();
if (_selectedFoo.Bars != null) { _bars.AddRange(_selectedFoo.Bars); }
this.NotifyPropertyChanged(() => this.Bars);
}
}
private ObservableCollection<Bar> _bars;
public ObservableCollection<Bar> Bars
{
get { return _bars; }
}
在最佳實踐中,視圖不應直接綁定到模型:這就是視圖模型的用途。 理想情況下,您希望#2可以實現最大程度的分離,並且需要一個邏輯來在適當時將更改同步回模型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.