110,533
社区成员
发帖
与我相关
我的任务
分享
public class DataModel : INotifyPropertyChanged
{
private int _id;
public int Id
{
get { return _id; }
set
{
_id = value;
OnPropChanged("Id");
}
}
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropChanged("Name");
}
}
private decimal _qty;
public decimal Qty
{
get { return _qty; }
set
{
_qty = value;
OnPropChanged("Qty");
}
}
private decimal _price;
public decimal Price
{
get { return _price; }
set
{
_price = value;
OnPropChanged("Price");
}
}
private decimal _amount;
public decimal Amount {
get { return _amount; }
set
{
_amount = value;
OnPropChanged("Amount");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
private ObservableCollection<DataModel> _dataList = new ObservableCollection<DataModel>();
public ObservableCollection<DataModel> DataList
{
get { return _dataList; }
set { SetProperty(ref _dataList, value); }
}
public MainWindowViewModel()
{
DataList.Add(new DataModel
{
Id = 1,
Name = "杯",
Qty=5,
Price=20,
Amount=100
});
DataList.Add(new DataModel
{
Id=2,
Name="纸",
Qty=100,
Price=30,
Amount=3000
});
}
<DataGrid x:Name="dgv" ItemsSource="{Binding DataList}" Margin="57,40,446,247"/>
public MainWindowViewModel()
{
DataList.CollectionChanged += (sender, e) =>
{
if (e.OldItems != null)
{
foreach (var item in e.OldItems?.OfType<DataModel>()) item.PropertyChanged -= DataModel_PropertyChanged;
}
if (e.NewItems != null)
{
foreach (var item in e.NewItems?.OfType<DataModel>()) item.PropertyChanged += DataModel_PropertyChanged;
}
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
{
ShowTotal();
}
};
DataList.Add(new DataModel
{
Id = 1,
Name = "杯",
Qty = 5,
Price = 20,
Amount = 100
});
DataList.Add(new DataModel
{
Id = 2,
Name = "纸",
Qty = 100,
Price = 30,
Amount = 3000
});
}
private void DataModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case nameof(DataModel.Amount):
ShowTotal();
break;
}
}
// ShowTotal示例而已,不是MVVM模式。
private void ShowTotal()
{
System.Windows.Threading.Dispatcher.CurrentDispatcher.BeginInvoke(
System.Windows.Threading.DispatcherPriority.Normal,
(Action)delegate
{
var grandTotal = DataList.Sum(x => x.Amount);
MessageBox.Show("总金额:" + grandTotal);
});
}