C# 在MVVM中将值从子模型传递到父模型

C# 在MVVM中将值从子模型传递到父模型,c#,mvvm,models,caliburn.micro,C#,Mvvm,Models,Caliburn.micro,我正在用两个模型编写一个MVVMC#WPF软件。我用的是Caliburn,仅供参考 父模型: namespace Expense_Manager.Models { public class Receipt: PropertyChangedBase { public Receipt() { Items = new List<Item>(); } public List<Item> Items{ g

我正在用两个模型编写一个MVVMC#WPF软件。我用的是Caliburn,仅供参考

父模型:

namespace Expense_Manager.Models
{
   public class Receipt: PropertyChangedBase
   {
      public Receipt()
      {
         Items = new List<Item>();
      }
      public List<Item> Items{ get; set; }
      private double _total;
      public double Total
      {
         get { return _total; }
         set
         {
            _total= value;
            NotifyOfPropertyChange(() => Total);
         }
      }
   }
}
为了发布这个问题,我简化了模型

因此,我的问题是:如何让父模型中的总金额通过以下方式进行计算:

  • 每次将项模型的每个值添加到父项列表时,都会添加该值
  • 在项目列表中输入完整的项目列表后,计算每个项目值的总和(这意味着如果在以后添加项目,它将不会重新计算自身,我对此不太满意,因此我更愿意执行上面的选项1)

  • 使用ObservableCollection而不是List,因为:

  • 它有一个CollectionChanged事件,可用于在每次添加/删除新项目时重新计算金额
  • 它实现了INotifyCollectionChanged,因此您可以将其绑定到不同的控件
  • 以下是您在案例中使用it的方式:

    public Receipt()
    {
        Items = new ObservableCollection<Item>();
        Items.CollectionChanged += Items_CollectionChanged;
    }
    
    private void Items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        Total = Items.Sum(x => x.Amount);
    }
    
    public ObservableCollection<Item> Items { get; set; }
    
    公共收据()
    {
    Items=新的ObservableCollection();
    Items.CollectionChanged+=Items\u CollectionChanged;
    }
    私有无效项\u CollectionChanged(对象发送方,NotifyCollectionChangedEventArgs e)
    {
    总计=项目总数(x=>x.Amount);
    }
    公共ObservableCollection项{get;set;}
    
    你太棒了!非常感谢。它比我想象的要好!
    public Receipt()
    {
        Items = new ObservableCollection<Item>();
        Items.CollectionChanged += Items_CollectionChanged;
    }
    
    private void Items_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        Total = Items.Sum(x => x.Amount);
    }
    
    public ObservableCollection<Item> Items { get; set; }