[英]Binding custom property with Entity Framework
I am building a C# application using the Entity framework. 我正在使用Entity框架构建一个C#应用程序。
I have an Entity which was created from my database which has fields "Price" and "Quantity". 我有一个从我的数据库创建的实体,其中包含“价格”和“数量”字段。
Using a partial class declaration I created a custom property "SubTotal" as follows: 使用部分类声明我创建了一个自定义属性“SubTotal”,如下所示:
partial class Detail {
public decimal Subtotal {
get
{
return Price * Quantity;
}
}
}
The thing is, I use a lot of DataBinding in my application. 问题是,我在我的应用程序中使用了很多DataBinding。
Somewhere, I use an IBindingList<Detail>
as ItemsSource
for a ListView. 在某处,我使用
IBindingList<Detail>
作为ListView的ItemsSource
。
When I modify (using code-behind) some elements of the list, the quantity and price, the listview is updated properly. 当我修改(使用代码隐藏)列表中的一些元素,数量和价格时,列表视图会正确更新。
However, the Subtotal is not updated. 但是,小计不会更新。
I think that it's because something is done automatically by the entity framework to notify that something has been changed, but I don't know what to add to my custom property so that it behaves the same way. 我认为这是因为某些东西是由实体框架自动完成的,以通知某些内容已被更改,但我不知道要添加到我的自定义属性中,以便它的行为方式相同。
Could you help me out? 你能救我吗?
对我有用的是调用OnPropertyChanged方法:
OnPropertyChanged("CustomPropertyName")
The UI doesn't know that the value of Subtotal
is changed. UI不知道
Subtotal
的值已更改。 Implement System.ComponentModel.INotifyPropertyChanged
, and then raise the PropertyChanged
event to let the UI know that Subtotal
has changed when either Price
or Quantity
has changed. 实现
System.ComponentModel.INotifyPropertyChanged
,然后引发PropertyChanged
事件,让UI知道当Price
或Quantity
发生变化时, Subtotal
已更改。
For example: 例如:
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));
}
}
}
Then when Price
or Quantity
is changed, you'd call NotifyPropertyChanged("Subtotal")
, and the UI should update the displayed value of Subtotal
appropriately. 然后,当更改
Price
或Quantity
时,您将调用NotifyPropertyChanged("Subtotal")
,并且UI应该适当地更新显示的Subtotal
值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.