更新/刷新ListView或ListView项,而无需从顶部开始

时间:2018-11-21 13:08:20

标签: c# listview xamarin xamarin.forms selecteditem

是否可以更新/刷新ListView或ListView项目?目前,更新/刷新ListView的唯一方法是:

View view = inflater.inflate(R.layout.your_file_name, container, false);

但这意味着如果我在ListView中向下滚动并选择一个项目,我将再次跳到ListView的顶部。但是我需要留在我离开的同一地点。有解决办法吗?

1 个答案:

答案 0 :(得分:1)

正确的方法实际上是在Model类中使用INotifyPropertyChanged并将可观察的集合用作ListView ItemsSource。

  • 首先,使用INotifyPropertyChanged继承您的类,并实现其属性,如下所示:

      public event PropertyChangedEventHandler PropertyChanged;  
    
      private void NotifyPropertyChanged(string propertyName)  
      {  
          if (PropertyChanged != null)  
          {  
             PropertyChanged(this, new PropertyChangedEventArgs(propertyName));  
          }  
       }  
    
  • 然后为您的ListView创建一个属性:

     private ObservableCollection<DataType> _FooCollection;
     public ObservableCollection<DataType> FooCollection { get{return _FooCollection; } set{_FooCollection = value; OnPropertyChanged(nameof(FooCollection )); }}
    
  • 在您的Xaml中,将此集合分配为listview绑定:

     <ListView .... ItemsSource={Binding FooCollection} ..../>
    
  • 然后,当您需要更改列表视图数据时,只需分配FooCollection,它将自动为您完成其余工作。

  • 例如:

    public void NewsList_Selected(Object sender, SelectedItemChangedEventArgs e)
    {
         var a = e.SelectedItem as NewsEntry;
         var b = from c in newsEntries
           where (a == c)
           select c;
         foreach(NewsEntry d in b)
        {
          d.Text = d.TextFull;
        }
    
         FooCollection = newsEntries; // This will do the rest for you 
    }