Search code examples
xamlxamarincollectionview

Xamarin Forms multiply CollectionViews Horizontal and Vertical


I try to use a CollectionView in a other CollectionView like this. My problem is there wont display me the second CV like there dont have a source. I guess the BindingContex can be the problem but i dont have a idea how i fix it.

      <CollectionView 
       SelectionMode="Single"
       ItemsSource="{Binding MainInfo}">

        <CollectionView.ItemsLayout>
            <LinearItemsLayout ItemSpacing="10" Orientation="Vertical" />
        </CollectionView.ItemsLayout>

        <CollectionView.ItemTemplate>
            <DataTemplate>

                <StackLayout>

                    <Label Text="{Binding UserName}"/>

                    <!--Horizontal CV-->
                    <CollectionView 
                        SelectionMode="Single"
                        ItemsSource="{Binding MainInfo}"
                        >
                        <CollectionView.ItemsLayout>
                            <LinearItemsLayout ItemSpacing="10" Orientation="Horizontal" />
                        </CollectionView.ItemsLayout>

                        <CollectionView.ItemTemplate>
                            <DataTemplate>

                                <StackLayout>

                                    <Label Text="{Binding ImageUrl}"/>
                                    <Label Text="{Binding FullName}"/>

                                </StackLayout>

                            </DataTemplate>
                        </CollectionView.ItemTemplate>

                    </CollectionView>

                </StackLayout>

            </DataTemplate>
        </CollectionView.ItemTemplate>

    </CollectionView>

Solution

  • I guess the BindingContext can be the problem but i don't have a idea how i fix it.

    In your case the ItemsSource and model should like the following

        public class MyDetails
        {
            public string ImageUrl { get; set; }
            public string FullName { get; set; }
        }
    
        public class MyObject
        {
            public string UserName { get; set; }
            public ObservableCollection<MyDetails> MainInfo { get; set; }
        }
    
        public class MyViewModel: INotifyPropertyChanged
        {
            public event PropertyChangedEventHandler PropertyChanged;
    
            public ObservableCollection<MyObject> MainInfo { get; set; }
    
            protected virtual void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));        
            }
    
            
        }
    

    In addition , agree with @Jason . In your case if want to display an collection in cell, you could use Bindable Layouts instead of putting a CollectionView in another . In this way you just need to set the Viewmodel and model like the above code .