【发布时间】:2020-12-12 14:39:33
【问题描述】:
我有一个这样的 ListView:
<ListView x:Name="ItemsListView"
ItemsSource="{Binding Items}"
VerticalOptions="FillAndExpand"
HasUnevenRows="true"
RefreshCommand="{Binding LoadItemsCommand}"
IsPullToRefreshEnabled="False"
IsRefreshing="{Binding IsBusy, Mode=OneWay}"
CachingStrategy="RecycleElement"
ItemSelected="OnItemSelected">
我的 ViewModel 有这个定义,我的 Model 类看起来像这样:
public ObservableCollection<IncomingJobItem> Items { get; set; }
public class IncomingJobItem
{
public int Index { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("amount")]
public int Amount { get; set; }
}
现在,当我更新 ViewModelObject.Items 并调用 NotifyPropertyChanged 时,ListView 中已经存在的项目不会得到更新。
例子:
// change already existing item
ViewModelObject.Items[0].Amount = 3;
// notify item in Items has changed
ViewModelObject.NotifyPropertyChanged("Items");
// nothing happens, item 0 in the list stays with the old amount...
// expected is to update the item in the list to display 3
但是当我创建新元素并将其添加到ViewModelObject.Items 时,ListView 会添加新项目但不会更新已经存在的项目。我能做什么?
同样ViewModelObject.NotifyPropertyChanged("Items.Amount"); 什么也不做。
【问题讨论】:
-
您需要在已更新的单个属性上调用 NotifyPropertyChanged,而不是在集合上
-
@Jason 我试过了,但它不起作用(NotifyPropertyChanged with Amount 和 Items.Amount 什么都不做)
-
IncomingJobItem 没有实现 INPC。您实际上必须在类上实现接口,并从属性的设置器中调用 PropertyChanged 方法。您不能只是从某个随机类中调用它并期望它起作用。有很多很多文章解释了如何做到这一点。喜欢stackoverflow.com/questions/1315621/…
-
@Jason 不,它没有......但是非常感谢你,你的提示让我找到了解决方案。这个概念对我来说是新概念,所以请原谅我的菜鸟错误。
标签: c# listview xamarin xamarin.forms binding