[英]Binding custom property with Entity Framework
我正在使用Entity框架构建一个C#应用程序。
我有一个从我的数据库创建的实体,其中包含“价格”和“数量”字段。
使用部分类声明我创建了一个自定义属性“SubTotal”,如下所示:
partial class Detail {
public decimal Subtotal {
get
{
return Price * Quantity;
}
}
}
问题是,我在我的应用程序中使用了很多DataBinding。
在某处,我使用IBindingList<Detail>
作为ListView的ItemsSource
。
当我修改(使用代码隐藏)列表中的一些元素,数量和价格时,列表视图会正确更新。
但是,小计不会更新。
我认为这是因为某些东西是由实体框架自动完成的,以通知某些内容已被更改,但我不知道要添加到我的自定义属性中,以便它的行为方式相同。
你能救我吗?
对我有用的是调用OnPropertyChanged方法:
OnPropertyChanged("CustomPropertyName")
UI不知道Subtotal
的值已更改。 实现System.ComponentModel.INotifyPropertyChanged
,然后引发PropertyChanged
事件,让UI知道当Price
或Quantity
发生变化时, Subtotal
已更改。
例如:
partial class Detail : INotifyPropertyChanged {
public decimal Subtotal
{
get
{
return Price * Quantity;
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
然后,当更改Price
或Quantity
时,您将调用NotifyPropertyChanged("Subtotal")
,并且UI应该适当地更新显示的Subtotal
值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.