C# 在MVVM中将值从子模型传递到父模型
我正在用两个模型编写一个MVVMC#WPF软件。我用的是Caliburn,仅供参考 父模型: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
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);
}
}
}
}
为了发布这个问题,我简化了模型
因此,我的问题是:如何让父模型中的总金额通过以下方式进行计算:
使用ObservableCollection而不是List,因为:
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; }