adospace / reactorui-maui

MauiReactor is a MVU UI framework built on top of .NET MAUI
MIT License
595 stars 49 forks source link

Sample DataTemplateSelector #82

Closed Code-DJ closed 1 year ago

Code-DJ commented 1 year ago

Hi, is there a sample for DataTemplateSelector. I tried the github search but didn't find it.

I'm able to create my own class that inherits MauiControls.DataTemplateSelector but not sure where to set it.

    public class MyDataTemplateSelector : DataTemplateSelector
    {
        protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
        {
            if (item is not MyClass myItem)
                return OnSelectTemplate(item, container);

            return myItem.CellType switch
            {
                MyViewCellType.A => new DataTemplate(typeof(AViewCell)),
                MyViewCellType.B => new DataTemplate(typeof(BViewCell)),
                MyViewCellType.C => new DataTemplate(typeof(CViewCell)),
                _ => new DataTemplate(typeof(DViewCell)),
            };
        }
    }

Thank you!

adospace commented 1 year ago

Hi, you probably shouldn't use a template selector at all. Where are you going to use the template selector? for example, if using a CollectionView just provide a Render function that renders your UI based on the Item.

Code-DJ commented 1 year ago

Migrating old Xamarin Forms code to reactor-maui that uses ListView with DataTemplateSelector. Will switch to CollectionView. Thanks!

adospace commented 1 year ago

Yes, you can still use the listview: https://github.com/adospace/reactorui-maui/blob/main/samples/MauiReactor.TestApp/Pages/ListViewExtendedTestPage.cs

Code-DJ commented 1 year ago

Yes, you can still use the listview: https://github.com/adospace/reactorui-maui/blob/main/samples/MauiReactor.TestApp/Pages/ListViewExtendedTestPage.cs

It works. Thank you!

I was overthinking it. The code (with conditional different views per cell) was crashing when scrolling the ListView but that was due a bug in my code :)