ObservableCollection列表不会更新Xamarin项目中的Listview

时间:2019-03-08 14:59:31

标签: listview xamarin observablecollection inotifypropertychanged

我有一个Xamarin项目。我想用对象列表填充列表视图,并且在添加,更新或删除列表后,列表视图必须刷新自身。我已经设法通过添加和更新来做到这一点,但是当我尝试删除Listview时,它不会刷新。我使用INotifyPropertyChanged基本模型继承自:

 public class BaseModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;


        protected bool SetProperty<T>(ref T storage, T value,
            [CallerMemberName] String propertyName = null)
        {
            if (object.Equals(storage, value)) return false;

            storage = value;
            this.OnPropertyChanged(propertyName);
            return true;
        }

        protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            var eventHandler = this.PropertyChanged;
            if (eventHandler != null)
            {
                eventHandler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

    }

ipsettings模型:

public class IpSettingModel : BaseModel
    {
        public IpSettingModel(String ip)
        {
            this._ip = ip;            
        }

        private string _ip = string.Empty;        
        public string ip
        {
            get { return this._ip; }
            set { this.SetProperty(ref this._ip, value); }
        }
}

使用适配器填充列表视图:

ObservableCollection<IpSettingModel> iplist = new ObservableCollection<IpSettingModel>();

    IpAdapter myadapter = new IpAdapter(this, iplist);
    ipListview.Adapter = myadapter;

到目前为止,一切都很好。如果我添加或更新列表中的对象,则工作正常。 当我尝试删除对象

IpManageClass.datasource.Remove(IpManageClass.datasource.Where(o => o.ip == selecteditem.ip).Single());

该对象已从ObservableCollection中移除,但Listview不刷新。我想念什么?

1 个答案:

答案 0 :(得分:0)

我找到了解决方法。 我在适配器上添加了更新功能:

public void Update()
  {            
      NotifyDataSetChanged();
  }  

并且我删除列表中的任何对象后调用此函数