Xamarin.Forms: Get all cells/items of a listview

前端 未结 2 874
情歌与酒
情歌与酒 2020-12-10 17:34

I want to make some changes to all of the cells shown in the ListView. Therefore I want to get all cells or items. E.g.

this.listView.ItemSource.Items
         


        
2条回答
  •  悲&欢浪女
    2020-12-10 18:14

    I am probably late to the party, but here's another approach using System.Reflection. Anyways, I'd suggest using it only in cases where databinding isn't possible and as a last resort option.

    For a given ListView

    
        
            
                
                    
                        
                            
                            
                        
                        
                    
                
            
        
        
            
        
    
    

    You can crawl through the ListView by grabbing the "TemplatedItems" property, casting it to ITemplatedItemsList and iterating through your (View)cells.

    IEnumerable pInfos = (connectionsListView as ItemsView).GetType().GetRuntimeProperties();
    var templatedItems = pInfos.FirstOrDefault(info => info.Name == "TemplatedItems");
    if (templatedItems != null)
    {
      var cells = templatedItems.GetValue(connectionsListView);
        foreach (ViewCell cell in cells as Xamarin.Forms.ITemplatedItemsList)
        {
            if (cell.BindingContext != null && cell.BindingContext is MyModelClass)
            {
                MyViewClass target = (cell.View as Grid).Children.OfType().FirstOrDefault();
                if (target != null)
                {
                   //do whatever you want to do with your item... 
                }
            }
        }
    }
    

    Update: Since it was asked, if (cell.BindingContext != null && cell.BindingContext is MyModelClass) is basically a safeguard to prevent access to non-existing views, for instance if the ListView hasn't been populated yet.

    If a check for the BindingContext being a particular model class isn't necessary, it would be sufficient to reduce the line to

    if (cell.BindingContext != null)
    

提交回复
热议问题