项目删除后,ListView不会更新其内容

时间:2019-10-26 06:21:39

标签: xamarin xamarin.forms xamarin.android

我正在使用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;
}

1 个答案:

答案 0 :(得分:1)

如果我按照以下说明修改了您的代码,则 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的{​​{1}}签名。