[英]CollectionView binding data doesn't update after OnPropertyChanged is triggered
我有一个绑定到ObservableCollection<Announce> Announces
的 CollectionView,当页面出现时,它会正确填充数据。 然后我发送一个 Post 请求,创建一个新的announces
,调用OnPropertyChanged
方法,更新了Announces
和announces
数据,但是getter 没有被调用,CollectionView 中的数据也没有更新。 是否应该在OnPropertyChanged
之后自动调用 getter? 我在不更新 UI 的代码中缺少什么?
公告服务是一个简单的服务,它从 http 请求中返回公告的 ObservableCollections。 这是我的AnnouncesViewModel:
public class AnnouncesViewModel : INotifyPropertyChanged
{
ObservableCollection<Announce> announces;
public ObservableCollection<Announce> Announces
{
get => announces;
set { announces = value; OnPropertyChanged("Announces"); }
}
public AnnouncesService service;
public event PropertyChangedEventHandler PropertyChanged;
public AnnouncesViewModel()
{
service = new AnnouncesService();
Announces = new ObservableCollection<Announce>();
getAnnounces();
}
public async Task addAnnounce(Announce announce)
{
Announces = await service.PostAnnounceAsync(announce); //same as using getAnnounces again
}
public async void getAnnounces()
{
Announces = await service.GetAnnouncesAsync();
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
这是我的 XAML 绑定
<ContentPage Title="">
<ContentPage.BindingContext>
<vm:AnnouncesViewModel/>
</ContentPage.BindingContext>
<ContentPage.Content>
<CollectionView ItemsSource="{Binding Announces}"
SelectionMode="Single"
SelectionChanged="CollectionView_SelectionChanged">
<CollectionView.ItemTemplate>
<DataTemplate>
<Label Text="{Binding location}"/>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</ContentPage.Content>
</ContentPage>
和从调用AddAnnounce一个TabbedPage AnnouncesViewModel
public partial class TabbedPage1 : TabbedPage
{
private AnnouncesService service;
private AnnouncesViewModel viewModel;
public TabbedPage1()
{
InitializeComponent();
service = new AnnouncesService();
viewModel = new AnnouncesViewModel();
}
private async void AddAnnounce(object sender, EventArgs e)
{
Announce announce = new Announce(localtion_entry.Text,sport_entry.Text,1);
await viewModel.addAnnounce(announce);
}
}
所以问题是我使用了两个不同的AnnouncesViewModel 实例。 一种在 XAML 中,一种在 cs 代码中用于调用AddAnnounce
。 为了解决这个问题,我从我的 XAML 代码中删除了这部分
<ContentPage.BindingContext>
<vm:AnnouncesViewModel/>
</ContentPage.BindingContext>
将x:Name = "page"
到我的 ContentPage 并在 TabbedPage1 构造函数中分配了 BindingContext:
private AnnouncesViewModel viewModel;
public TabbedPage1()
{
InitializeComponent();
viewModel = new AnnouncesViewModel();
page.BindingContext = viewModel;
}
我还在AnnouncesViewModel 中使用Add 方法向我的Announces ObservableCollection 添加内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.