我正在使用 Entity 框架构建 C# 应用程序。
我有一个实体,它是从我的数据库创建的,它有字段“价格”和“数量”。
使用部分类声明,我创建了一个自定义属性“SubTotal”,如下所示:
partial class Detail {
public decimal Subtotal {
get
{
return Price * Quantity;
}
}
}
问题是,我在我的应用程序中使用了很多数据绑定(bind)。
在某处,我使用 IBindingList<Detail>
作为ItemsSource
对于 ListView。
当我修改(使用代码隐藏)列表的某些元素、数量和价格时, ListView 会正确更新。
但是,小计不会更新。
我认为这是因为 Entity Framework 会自动完成某些操作以通知某些内容已更改,但我不知道要将什么添加到我的自定义属性以使其以相同的方式运行。
你能帮帮我吗?
最佳答案
UI 不知道 Subtotal
的值已更改。实现 System.ComponentModel.INotifyPropertyChanged
,然后引发 PropertyChanged
事件,让 UI 知道 Subtotal
在 Price
或 Quantity
发生变化时发生变化改变了。
例如:
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 应更新显示的小计
的值适当。
关于c# - 使用 Entity Framework 绑定(bind)自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5069232/