我正在使用 DataGrid 并使用 ViewModel 中的 ObservableCollection 进行绑定
private ObservableCollection<StockItem> _stockList;
public ObservableCollection<StockItem> StockList
{
get
{
return _stockList;
}
set
{
_stockList = value;
OnPropertyChanged("StockList");
}
}
StockItem 类包含其属性,即 DataGrid 中的列。DataGrid 中有一个名为 Amount 的列,其值随同一个数据网格的 Quantity*Price 列发生变化。
我在 ViewModel 中有一个名为 TotalAmount 的属性,该属性是在 ObservableCollection CollectionChanged 事件中计算的,例如
void OnStockListChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
this.TotalAmount = this.StockList.Sum(t => t.Amount);
}
只有在将新行添加到包含某些数据的 DataGrid 时,才会在绑定到 TotalAmount 的 TextBox 中更新此值。我希望在数据网格中的金额列更改后立即更新 TotalAmount 的这个 TextBox。
我怎样才能做到这一点。
StockItem Class
public class StockItem : ObservableObject, ISequencedObject
{
JIMSEntities dbContext = new JIMSEntities();
public StockItem()
{
var qs = dbContext.Stocks.Select(s => s.StockName);
_stocks = new CollectionView(qs.ToArray());
_stocks.CurrentChanged += new EventHandler(Stocks_CurrentChanged);
}
void Stocks_CurrentChanged(object sender, EventArgs e)
{
if (_stocks.CurrentItem != null)
StockName = _stocks.CurrentItem.ToString();
var qs = (from p in dbContext.Stocks
where p.StockName.Contains(StockName)
select new { Unit = p.Unit, UnitPrice = p.UnitPrice }).SingleOrDefault();
if (qs != null)
{
Unit = qs.Unit;
UnitPrice = (decimal)qs.UnitPrice;
}
}
private CollectionView _stocks;
public CollectionView Stocks
{
get
{
return _stocks;
}
set
{
_stocks = value;
OnPropertyChanged("Stocks");
}
}
private int _sNo;
public int SNo
{
get
{
return _sNo;
}
set
{
_sNo = value;
OnPropertyChanged("SNo");
}
}
private string _stockName;
public string StockName
{
get
{
return _stockName;
}
set
{
_stockName = value;
OnPropertyChanged("StockName");
}
}
private decimal _unitPrice;
public decimal UnitPrice
{
get
{
return _unitPrice;
}
set
{
_unitPrice = value;
OnPropertyChanged("UnitPrice");
OnPropertyChanged("Amount");
}
}
private string _unit;
public string Unit
{
get
{
return _unit;
}
set
{
_unit = value;
OnPropertyChanged("Unit");
}
}
private decimal _discount;
public decimal Discount
{
get
{
return _discount;
}
set
{
_discount = value;
OnPropertyChanged("Discount");
OnPropertyChanged("Amount");
}
}
private decimal _quantity;
public decimal Quantity
{
get
{
return _quantity;
}
set
{
_quantity = value;
OnPropertyChanged("Quantity");
OnPropertyChanged("Amount");
}
}
public decimal Amount
{
get
{
decimal total = Quantity * (UnitPrice - (UnitPrice * (Discount / 100)));
return total;
}
}
public override string ToString()
{
return StockName;
}
}