所以,我有项目列表(存储在ObservableCollection中),如何通知项目的属性更改?如何通知有关更改ListBox项目的属性?
我有当前的解决方案:属性也上升NotifyPropertyChanged(),它似乎工作。但是,有时,属性发生了变化,但未通知视图(调试器显示私有字段包含新值,但屏幕仍显示旧值)。也许这是更好的方式吗?
编辑1:是的,绑定是在双向模式下完成的。
EDIT2:刚才发现有时PropertyChanged是null。为什么会这样?
EDIT3:代码很基础。我使用的是很常见的NotifyPropertyChanged()
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void NotifyPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(this, e);
}
}
二传手:
public double Amount
{
get
{
return amount;
}
set
{
amount = value;
NotifyPropertyChanged("Amount");
}
}
型号是继承(刚刚发现,它可以是一个问题)
public class Item : INotifyPropertyChanged
变化量:
var foundItem = shoppingList.FirstOrDefault(p => p.ean == item.ean);
if (foundItem != null)
{
foundItem.Amount += 1;
}
列表填写虚拟机:
public class MyViewModel : BaseFoodieViewModel
{
private ObservableCollection<ProductSearchCategoryCollection<Item>> _itemsList = new ObservableCollection<ProductSearchCategoryCollection<Item>>();
public ObservableCollection<ProductSearchCategoryCollection<Item>> ItemsList
{
get { return _itemsList; }
set { Set(() => ItemsList, ref _itemsList, value); }
}
****
ItemsList.Clear();
var list = from item in parsedList
group item by item.code
into it orderby it.Key
select new ProductSearchCategoryCollection<Item>(it.Key, it);
ItemsList = new ObservableCollection<ProductSearchCategoryCollection<Item>>(list);
编辑4:只是想通了,它适用于几个项目。这些项目保持不变 - 它们工作正常。但是当我开始改变它时,有一次,PropertyChanged为null。
编辑5:所以,我刚刚重新启动项目。那些已经更改的项目 - 它们仍然无法识别(PropertyChanged == null)。然而,其余的工作正常。
编辑6:到目前为止,问题是在
var foundItem = shoppingList.FirstOrDefault(p => p.ean == item.ean);
if (foundItem != null)
{
foundItem.Amount += 1;
}
发布您的代码,否则很难提供帮助。 –
@AlaaMasoud刚刚添加。有时它可以工作,但在某个时刻,它只是停止通知。我猜,导致PropertyChanged为null。 –