Xamarin Forms:适配器的内容已更改但 ListView 未收到通知
Xamarin Forms: The content of the adapter has changed but ListView did not receive a notification
在我使用 Xamarin Forms 制作的 Xamarin 应用程序中,出现错误 "The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread."。
我正在使用 Xamarin.Forms ListView 来显示学生列表。当我转到“添加学生”页面并将学生添加到列表时,抛出此错误。
ListView listView = new ListView
{
ItemsSource = register.StudentList,
ItemTemplate = cell // Set the ImageCell to the item template for the listview
};
// Set the content for the page.
Content = new StackLayout
{
Children = { header, listView }
};
以上代码来自注册页面,是显示学生名单的地方。下面的代码来自 AddStudent 页面,这是将学生添加到寄存器的地方。
//Now add the new student to the register.
if(register != null)
{
register.addStudent(Student);
}
//After adding to the register, open up the page for this register.
Navigation.InsertPageBefore(new RegisterPage(register), Navigation.NavigationStack.First());
await Navigation.PopToRootAsync();
我实际上并没有在代码中使用适配器,所以我不确定这个错误是从哪里来的。我看到的很多类似问题似乎都与 android 适配器有关,但这是一个用 Xamarin Forms 制作的应用程序。
在这种情况下是否可以使用某种替代方法?
如您所述,您的 register
对象是 List
。因此,您将其绑定到的视图永远不会收到有关内容更改的消息。
所以 Jason 在评论中问,register
是否是 ObservableCollection
,为什么你会问自己。 ObservableCollection
实现了 INotifyCollectionChanged
,这意味着当绑定到视图时,视图现在可以订阅接口提供的事件。这个事件可以告诉它发生了什么变化。这可能是添加了新项目。某个项目已删除或集合中的顺序已更改。
反过来,如果您想更新集合中的项目,他们还必须实施 INotifyPropertyChanged
以便视图反映所做的更改。
在我使用 Xamarin Forms 制作的 Xamarin 应用程序中,出现错误 "The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread."。
我正在使用 Xamarin.Forms ListView 来显示学生列表。当我转到“添加学生”页面并将学生添加到列表时,抛出此错误。
ListView listView = new ListView
{
ItemsSource = register.StudentList,
ItemTemplate = cell // Set the ImageCell to the item template for the listview
};
// Set the content for the page.
Content = new StackLayout
{
Children = { header, listView }
};
以上代码来自注册页面,是显示学生名单的地方。下面的代码来自 AddStudent 页面,这是将学生添加到寄存器的地方。
//Now add the new student to the register.
if(register != null)
{
register.addStudent(Student);
}
//After adding to the register, open up the page for this register.
Navigation.InsertPageBefore(new RegisterPage(register), Navigation.NavigationStack.First());
await Navigation.PopToRootAsync();
我实际上并没有在代码中使用适配器,所以我不确定这个错误是从哪里来的。我看到的很多类似问题似乎都与 android 适配器有关,但这是一个用 Xamarin Forms 制作的应用程序。
在这种情况下是否可以使用某种替代方法?
如您所述,您的 register
对象是 List
。因此,您将其绑定到的视图永远不会收到有关内容更改的消息。
所以 Jason 在评论中问,register
是否是 ObservableCollection
,为什么你会问自己。 ObservableCollection
实现了 INotifyCollectionChanged
,这意味着当绑定到视图时,视图现在可以订阅接口提供的事件。这个事件可以告诉它发生了什么变化。这可能是添加了新项目。某个项目已删除或集合中的顺序已更改。
反过来,如果您想更新集合中的项目,他们还必须实施 INotifyPropertyChanged
以便视图反映所做的更改。