我有DataGrid
绑定到ObservableCollection<Item>
。当我更改项目的数量时,我想自动更改项目的总数。这是Quantity*Cost=Total
<DataGrid ItemsSource="{Binding Invoices.Items}" AutoGenerateColumns="False">
<DataGridTextColumn Header="Name" Binding="{Binding Name}" />
<DataGridTextColumn Header="Quantity" Binding="{Binding Quantity}" />
<DataGridTextColumn Header="Cost" Binding="{Binding Cost}" />
<DataGridTextColumn Header="Total" Binding="{Binding Total}" />
</DataGrid>
ViewModel变化简单&#34;
public class ViewModel:BaseClass
{
public ViewModel()
{
FillInvoice();
}
private Invoice _invoice;
public Invoice Invoice
{
get { return _invoice; }
set
{
if (_invoice!=value)
{
_invoices = value;
OnPropertyChanged();
}
}
}
private void FillInvoice()
{
var customer = new Customer() {Id=1,Name = "James"};
var invoice = new Invoice() {Customer = customer, Id = 1,CustomerId = 1};
var item = new Item() {Cost = Convert.ToDecimal(12.50),Id = 1,Name = "Item"};
for (int i = 0; i < 10; i++)
{
invoice.Items.Add(item);
}
Invoices = invoice;
}
}
发票看起来像:
public Invoices()
{
Items=new ObservableCollection<Item>();
}
public int Id { get; set; }
public int CustomerId { get; set; }
public Customer Customer { get; set; }
public ObservableCollection<Item> Items { get; set; }
我的项目看起来像:
public class Item:BaseClass
{
private string _name;
private decimal _cost;
public int Id { get; set; }
public string Name
{
get { return _name; }
set
{
if (_name!=value)
{
_name = value;
OnPropertyChanged();
}
}
}
private int _quantity;
public int Quantity
{
get { return _quantity; }
set
{
if (_quantity!=value)
{
_quantity = value;
OnPropertyChanged();
}
}
}
public decimal Cost
{
get { return _cost; }
set
{
if (_cost!=value)
{
_cost = value;
OnPropertyChanged();
}
}
}
private decimal _total;
public decimal Total
{
get { return _total; }
set
{
if (_total != value)
{
_total = value;
OnPropertyChanged();
}
}
}
}
我在想的是在Quantity项目中添加一个事件处理程序,它将为我计算总数,但我不知道如何做到这一点我尝试添加。
public ViewModel(){
Invoice.Items.Quantity.PropertyChanged += (s,e)
{
Total = Cost*Quantity
}
}
public Item()
{
Quantity.PropertyChanged += (s,e)
{
Total = Cost*Quantity
}
}
但它并没有在它们上编译。
答案 0 :(得分:1)
尝试将OnPropertyChanged("Total");
添加到您的Quantity
媒体资源中:
private int _quantity;
public int Quantity
{
get { return _quantity; }
set
{
if (_quantity!=value)
{
_quantity = value;
OnPropertyChanged();
Total = Cost*Quantity
OnPropertyChanged("Total");
}
}
}
答案 1 :(得分:1)
如果总计等于Cost * Quantity,您可以将Total实现为计算属性,因为存储冗余数据没有意义:
public decimal Total
{
get { return Cost * Quantity; }
}
这应该正常工作,假设没有参数的OnPropertyChanged()触发泛型/ null属性更改事件,这将导致重新检查所有订阅的属性。
答案 2 :(得分:0)
您可以在您的Property中编写代码,如下所示:
for name in list:
locals()[name](myVar)