我有一个DataGrid
绑定到一个ObservableCollection<Item>
。当我更改物料的数量时,我想自动更改物料的总量。这是Quantity*Cost=Total
C#每次更改其他值使用mvvm
<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>
视图模型是改变简单的”
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();
}
}
}
}
我是什么思考是广告将一个事件处理程序添加到数量项目中,它将计算总计,但我不确定如何执行添加。
public ViewModel(){
Invoice.Items.Quantity.PropertyChanged += (s,e)
{
Total = Cost*Quantity
}
}
public Item()
{
Quantity.PropertyChanged += (s,e)
{
Total = Cost*Quantity
}
}
但它不能编译它们。
为什么你不在物品的设置器中刷新物品,例如: private int _quantity; public int Quantity { get {return _quantity; } set { if(_quantity!= value) { _quantity = value; RefreshSomething(); OnPropertyChanged(); } } } – SeeuD1
试试这个:'public decimal Total {get {return Cost * Quantity; }}(和'OneWay'绑定)。 – Jose