开发者

Binding custom property with Entity Framework

I am building a C# application using the Entity framework.

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:

partial class Detail {
  public decimal Subtotal {
    get
    {
      return Price * Quantity;
    }
  }  
}

The thing is, I use a lot of DataBinding in my application.

Somewhere, I use an IBindingList<Detail> as ItemsSource for a ListView.

When I modify (using code-behind) some elements of the list, the quantity and price, the listview开发者_JAVA技巧 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?


The UI doesn't know that the value of Subtotal is changed. 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.

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.


What worked for me is to call the OnPropertyChanged method:

OnPropertyChanged("CustomPropertyName")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜