Search code examples
maui.net-maui

How to customize collectionview in dotnetmaui


I am porting my Xamarin Forms application to dotnet maui and I want to customize the collection view for android so that the items will stack from the end. I have done it in Xamarin Forms as follows,

public class ChatCollectionViewRenderer : CollectionViewRenderer
    {
        public ChatCollectionViewRenderer(Context context) : base(context)
        {
            this.SetItemViewCacheSize(20);
            this.HasFixedSize = true;
        }

        protected override LayoutManager SelectLayoutManager(IItemsLayout layoutSpecification)
        {
            var manager = new LinearLayoutManager(Context, LinearLayoutManager.Vertical, false);
            manager.StackFromEnd = true;
            return manager;
        }
    }

How to do it in maui using handlers?


Solution

  • Found it, it can be done like this,

    Microsoft.Maui.Controls.Handlers.Items.CollectionViewHandler.Mapper.AppendToMapping("ChatStackFromEnd", (h, v) =>
                    {
                        var recycleView = h.PlatformView;
                        var manager = new AndroidX.RecyclerView.Widget.LinearLayoutManager(recycleView.Context, AndroidX.RecyclerView.Widget.LinearLayoutManager.Vertical, false);
                        manager.StackFromEnd = true;
                        recycleView.SetLayoutManager(manager);
                    });
    

    Trying it out...