Tuesday, 31 January 2023

How to pass an object from a carousel view to a custom control in Xamarin.Forms?

I currently have a carousel view that makes use of an object in the binding context to obtain a list of instances of the ListItem property. The binding to MyList for the CarouselView is working fine and I am able to scroll left and right for every item in my list. The trouble that I'm having is that while the CustomControl is being loaded, it is not receiving the ListItem that will fit in the Item property. So, the this.Item property in CustomControl is just returning null.

<ContentPage.Content>
                    <CarouselView ItemsSource="{Binding MyList}">
                        <CarouselView.ItemTemplate>
                            <DataTemplate>
                                <StackLayout>
                                    <controls:CustomControl Item="{Binding}"/>
                                </StackLayout>
                            </DataTemplate>
                        </CarouselView.ItemTemplate>

                    </CarouselView>

                </Grid>
    </ContentPage.Content>
[XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class HomeView : ContentPage
    {
        private ListContainer vm; 
        
        public HomeView()
        {
            InitializeComponent();
            Task.Run(async () =>
            {
                vm = DiContainer.Resolve<ListContainer>();
                await vm.Initialise();

                Device.BeginInvokeOnMainThread(() =>
                {
                    this.BindingContext = vm;
                });

            });
        }
    }
[XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class CustomControl : ContentView
    {

        public static readonly BindableProperty ItemProperty = BindableProperty.Create(nameof(Item), 
            typeof(ListItem), typeof(CustomControl), default(ListItem),BindingMode.TwoWay);

        public ListItem Item
        {
            get => (ListItem)GetValue(ItemProperty);
            set => SetValue(ItemProperty, value);
        }

        public CustomControl ()
        {
            InitializeComponent ();
            BindingContext = this.Item;
        }

    }


from How to pass an object from a carousel view to a custom control in Xamarin.Forms?

No comments:

Post a Comment