How to bind list inside ListView in Xamarin.Forms

前端 未结 1 1166
执念已碎
执念已碎 2020-12-29 07:09

I have one ListView on my page having ItemSource as List as shown below:

public class AssetModel
{
    public str         


        
1条回答
  •  失恋的感觉
    2020-12-29 07:50

    It seems like a classic grouping listview use case. James Montemagno wrote an article about this kind of need that should help you a lot.

    In summary, the grouping feature expects an object of type 'List of List' (IEnumerable>), where each 'master item' is a list of 'detail item'.

    To make it easy, you can use the class provided at the above mentioned article:

    public class Grouping : ObservableCollection
    {
        public K Key { get; private set; }
    
        public Grouping(K key, IEnumerable items)
        {
            Key = key;
            foreach (var item in items)
                this.Items.Add(item);
        }
    }
    

    Then, the list property you must change its type to, for example, this:

    ObservableCollection> AssetsList { get; set; } = 
        new ObservableCollection>();
    

    This AssetsList is what you should bind to the ItemsSource of ListView

    To fill this property, you'll need, for example, do this:

    for (int i = 0; i < 5; i++)
    {
        var asset = new AssetModel();
        asset.AssetId = new Guid().ToString();
        asset.Description = $"Asset { i + 1} ";
        asset.TaskDetailList = new List();
    
        for (int j = 0; j < 3; j++)
            asset.TaskDetailList.Add(new TaskDetail() { Description = $"Detail { (i + 1) } - { (j + 1) }" });
    
        var group = new Grouping(asset, asset.TaskDetailList);
    
        AssetsList.Add(group);
    }
    

    Then in your XAML you define your ListView Grouping properties:

    
        
            
                
                    
                        
                            
                        
                            
                    
                
            
        
        
            
                
                    
                        
                
            
        
    
    

    0 讨论(0)
提交回复
热议问题