我正在使用C#开发Xamarin.Forms。我的ListView能够显示数据库中的数据。我还在后面的代码中添加了MenuItem
和点击事件处理程序。当我按住要删除(Android)的项目时,将调用MenuItem_Clicked
并更新_students
(删除了我选择的项目),但是我的ListView仍然没有更新。
我的看法:
<ListView x:Name="listStudents" Refreshing="listStudents_Refreshing"
IsPullToRefreshEnabled="True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<ViewCell.ContextActions>
<MenuItem Text="Delete" Clicked="MenuItem_Clicked" CommandParameter="{Binding .}" />
</ViewCell.ContextActions>
<StackLayout Padding="20">
<Label Text="{Binding Name}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
后面的代码:
private ObservableCollection<Student> _students;
public ListView_SearchBar()
{
InitializeComponent();
var _students = SQLite_DB.SeedStudentData();
_students = new ObservableCollection<Student>(_students);
listStudents.ItemsSource = _students;
}
private void MenuItem_Clicked(object sender, EventArgs e)
{
listStudents.IsRefreshing = true;
_students.Remove((sender as MenuItem).CommandParameter as Student);
listStudents.ItemsSource = null;
listStudents.ItemsSource = _students;
listStudents.IsRefreshing = false;
return;
}
如果我按如下所示修改您的代码,则ListView会在我这一边正确更新:
private ObservableCollection<Student> _students;
public ListView_SearchBar()
{
InitializeComponent();
_students = SQLite_DB.SeedStudentData();
_students = new ObservableCollection<Student>(_students);
listStudents.ItemsSource = _students;
}
private void MenuItem_Clicked(object sender, EventArgs e)
{
listStudents.IsRefreshing = true;
_students.Remove((sender as MenuItem).CommandParameter as Student);
listStudents.ItemsSource = null;
listStudents.ItemsSource = _students;
listStudents.IsRefreshing = false;
return;
}
请注意,我在页面构造函数中删除了第一次使用var
的_student
签名。