簡體   English   中英

為什么從綁定列表中刪除對象后 Xamarin 中 ListView 上的項目不會消失,即使 ItemSource 屬性已重置?

[英]Why items on ListView in Xamarin do not disappear after object is removed from binded list, even if ItemSource property is reset?

我目前正在學習 Xamarin 並且處於檢查 ListView 的階段。 我注意到如果我將 ListView 綁定到一個 List 並從中刪除一個項目,listview 將不會顯示此更改。 我知道我需要使用 ObservableCollection 讓它自動工作(或讓集合實現正確的接口),但我只是想了解為什么即使我在刪除后重置 ListView 的 ItemsSource 屬性它也不起作用。 這是代碼:

 namespace Lists
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class ListsOne : ContentPage
    {
       List<Contact> _contacts = new List<Contact> {
                    new Contact{ Name = "Mosh", Number = "1234566", ImageUrl="http://lorempixel.com/100/100/people/1"},
                    new Contact { Name = "Josh", Number = "1236578" , ImageUrl = "http://lorempixel.com/100/100/people/2"}};

        IEnumerable<Contact> GetContacts(string searchText = null)
        {  

            if (String.IsNullOrWhiteSpace(searchText))
            {
                return _contacts;
            }

            return _contacts.Where(c => c.Name.StartsWith(searchText));
        }

        public ListsOne()
        {
            InitializeComponent();            
            listView.ItemsSource = GetContacts();
        }       

        private void Delete_Clicked(object sender, EventArgs e)
        {
            Contact contact = (sender as MenuItem).CommandParameter as Contact;
            _contacts.Remove(contact);
            listView.ItemsSource = GetContacts();

        }

        private void SearchBar_TextChanged(object sender, TextChangedEventArgs e)
        {
            listView.ItemsSource = GetContacts(e.NewTextValue);
        }
    }
}

正如您在 Delete_Clicked 方法中看到的,從 _contacts 中刪除聯系人后,我重置了 ItemsSource,但它不會對應用程序產生任何影響,即使 SearchBar_TextChanged 的​​實現幾乎相同(如果我沒記錯的話,我在工作現在)。 關於它是如何工作的任何見解? 對不起,如果它很愚蠢,但我只是在學習。

用 ObservableCollection 替換列表。 后一個事件通知 UI 其數組中的更改。 (這是當您使用 MVVM 時,可能不適用於您的示例)。

此外,據我所知,向 ListView.ItemSource 添加刪除項目時存在問題。 要使其工作,請執行以下操作:

        private void Delete_Clicked(object sender, EventArgs e)
    {
        Contact contact = (sender as MenuItem).CommandParameter as Contact;
        _contacts.Remove(contact);
        listView.ItemsSource = null;
        listView.ItemsSource = GetContacts();

    }

listview-ItemsSource的文檔中,它說:

如果您希望 ListView 在基礎列表中添加、刪除和更改項目時自動更新,則需要使用 ObservableCollection。 ObservableCollection是在 System.Collections.ObjectModel 中定義的,和 List 一樣,除了它可以通知 ListView 任何變化:

ObservableCollection<Employee> employees = new ObservableCollection<Employee>();
listView.ItemsSource = employees;

//Mr. Mono will be added to the ListView because it uses an ObservableCollection
employees.Add(new Employee(){ DisplayName="Mr. Mono"});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM