我正在使用C#编写Xamarin表单。我的列表视图能够显示数据库中的数据。我还在后面的代码中添加了带有点击事件处理程序的MenuItem。当我按住要删除(Android)的项目时,会调用MenuItem_Clicked并更新_students
(我选择的项目已删除),但我的列表视图仍然没有“刷新”。
我的看法:
<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
签名。