可能最简单的方法是将每个Item
包装在ItemViewModel
中。
该ItemViewModel
有一个公共财产Multiplier
其中 - 在二传手 - 包含Item
的价格将被更新。
对于价格的变化将反映在视图 - 它必须实现INotifyPropertyChanged
,当然,当“价格”设置引发该事件。
或者:在构造函数从Item
复制Price
到ItemViewModel
到另外Price
财产上的ItemViewModel
随着示例代码你需要的IValueConverter到输入文本从string
转换为double
(或使用允许结合double
的apropriate控制)
public class ItemsViewModel
{
public ObservableCollection<ItemViewModel> Items { get; set; }
public ItemsViewModel()
{
this.Items = new ObservableCollection<ItemViewModel>(getItemsFromSomewhere().Select(item => new ItemViewModel(item)));
}
}
public class ItemViewModel : INotifyPropertyChanged
{
private readonly Item item;
private double price;
private double multiplicator;
public ItemViewModel(Item item)
{
this.item = item;
this.price = item.Price;
}
public double Multiplicator {
get { return this.multiplicator; }
set {
this.multiplicator = value;
this.Price = this.item.Price * value;
}
}
public double Price {
get { return this.price; }
set {
this.price = value;
this.OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public class Item
{
public double Price { get; set; }
}
感谢您的回答!这的确是我的目标,但它是否适用于列表视图中的每个元素?我的listview将从我的viewModel中填入Item对象,并且我将无法使用每个Item的价格输入每个标签......我担心,如果我一旦更改了条目,就会更新所有其他商品的价格。 – FCouto
只要每个项目的ViewModel具有自己的“乘数”属性,它就不应该影响其他行。 –
谢谢你的帮助! – FCouto