有没有办法为使用集合中“子实体”属性的计算属性触发某种类型的 OnPropertyChanged
事件?
一个小例子:
我有一个简单的 WPF 应用程序,其中包含显示客户属性的 DataGrid。 我使用的是 Entity Framework 5 CodeFirst 方法,因此我使用自己的 INotifyPropertyChanged 实现手动编写了我的类。
public partial class Customer : INotifyPropertyChanged
{
private string _firstName;
public virtual string FirstName
{
get { return _firstName; }
set
{
_firstName = value;
OnPropertyChanged("FirstName");
OnPropertyChanged("FullName");
}
}
private string _lastName;
public virtual string LastName
{
get { return _lastName; }
set
{
_lastName = value;
OnPropertyChanged("LastName");
OnPropertyChanged("FullName");
}
}
public virtual ICollection<Car> Cars { get; set; }
public virtual ICollection<Invoice> Invoices { get; set; }
...
}
现在在同一个类中我创建了 3 个计算属性:
public string FullName
{
get { return (FirstName + " " + LastName).Trim(); }
}
public int TotalCars
{
get
{
return Cars.Count();
}
}
public int TotalOpenInvoices
{
get
{
if (Invoices != null)
return (from i in Invoices
where i.PayedInFull == false
select i).Count();
else return 0;
}
}
FullName
在 DataGrid 中自动更新,因为我正在调用 OnPropertyChanged("FullName");
我找到了一个 INotifyCollectionChanged 实现的示例,当向 ICollection 添加或从中删除某些内容时,我可以使用它来自动更新 TotalCars
:
http://www.dotnetfunda.com/articles/article886-change-notification-for-objects-and-collections.aspx
但是当 ICollection (Invoices
) 中的属性 (PayedInFull
) 时,触发 OnPropertyChange("TotalOpenInvoices")
的最佳方法是什么? ) 变化?
在 Invoice 类中执行类似 OnPropertyChanged("Customer.TotalOpenInvoices");
的操作似乎无法解决问题...:)
最佳答案
您可以控制收藏中的内容吗?如果这样做,您可以在 Invoice 对象上创建一个 Parent 属性,当它被添加到集合中时,将父对象设置为您的 Customer。然后当 PaidInFull 设置时,运行您的 Customer.OnPropertyChanged("TotalOpenInvoices") 或调用 Customer 对象上的方法来重新计算您的发票。
关于c# - 有没有办法为使用集合中 `OnPropertyChanged` 属性的计算属性触发某种 "child entity"事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13257888/