Skip to main content
 首页 » 编程设计

c#之使用 Entity Framework 绑定(bind)自定义属性

2024年02月23日17cloudgamer

我正在使用 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 应更新显示的小计的值适当。