Bob*_*way 6 c# wpf entity-framework mvvm
在 MVVM 中使用 WPF。我有一个带有 CurrentItem 属性的 ViewModel。这是一个直接从实体框架中提取的 Item 对象。Item 有一组 Property 对象。
public virtual ICollection<Property> Properties { get; set; }
Run Code Online (Sandbox Code Playgroud)
在视图中,我需要用户能够从该集合中添加和删除对象。为此,我需要创建一个ObservableCollection<Property>
,我们将其称为 ItemProperties。
有多种方法可以做到这一点。最明显的就是ObservableCollection<Property>
在ViewModel上添加一个属性。然后在构造函数中填充它,如下所示:
ItemProperties = new ObservableCollection<Property>(CurrentItem.Properties);
Run Code Online (Sandbox Code Playgroud)
也可以创建一个位于真实集合顶部的 ObservableCollection 包装器:
public ObservableCollection<Property> ItemProperties
{
get
{
return new ObservableCollection<Property>(CurrentItem.Properties);
}
set
{
CurrentItem.Properties = value.ToList();
OnPropertyChanged("ItemProperties");
}
}
Run Code Online (Sandbox Code Playgroud)
这有其自身的问题。你不能只Add()
到这个集合,因为它会get
首先,这意味着集合保持不变。因此,您要么必须启动一个新集合,添加到该集合中,然后将其值分配给该属性,要么OnPropertyChanged
在该属性之外引发该事件。其中任何一个听起来也像是维护问题。
有没有更有效的方法可以让您直接访问 EF 属性列表?
在此方面,您具有数据层和表示之间解耦的优势,无需启动集合。
尝试LoadedEvent
从服务器加载数据。示例事件如下
private ObservableCollection<Property> _itemProperties;
public ObservableCollection<Property> ItemProperties
{
get { return _itemProperties; }
set
{
_itemProperties= value;
RaisePropertyChanged(() => ItemProperties);
}
}
Run Code Online (Sandbox Code Playgroud)
加载事件
var result= await Task.Run(() => MyBusiness.GetMyData());
//Map to the viewModel if necessary
ItemProperties = result;
Run Code Online (Sandbox Code Playgroud)
添加到集合
var isSuccess = await Task.Run(()=>MyBusiness.Insert(x));
if(isSuccess)
{
ItemProperties.Add(x);
}
Run Code Online (Sandbox Code Playgroud)