Xamarin.Forms – Implementing ItemsSource for Custom Control

Here’s some code for ItemsSource:

        public static readonly BindableProperty ItemsSourceProperty = BindableProperty.Create(
           propertyChanged: (bindable, oldValue, newValue) => OnItemsSourceChanged(bindable, oldValue, newValue));

        static void OnItemsSourceChanged(BindableObject bindable, object oldValue, object newValue)
            void newValueINotifyCollectionChanged_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
                var wraplayout = bindable as WrapLayout;

                if (e.OldItems != null)
                    foreach (var item in e.OldItems)
                        wraplayout.Children.Remove(item as View);

                if (e.NewItems != null)
                    foreach (var item in e.NewItems)
                        wraplayout.Children.Add(item as View);

            var oldValueINotifyCollectionChanged = oldValue as INotifyCollectionChanged;

            if (null != oldValueINotifyCollectionChanged)
                oldValueINotifyCollectionChanged.CollectionChanged -= newValueINotifyCollectionChanged_CollectionChanged;

            var newValueINotifyCollectionChanged = newValue as INotifyCollectionChanged;

            if (null != newValueINotifyCollectionChanged)
                newValueINotifyCollectionChanged.CollectionChanged += newValueINotifyCollectionChanged_CollectionChanged;
        public IEnumerable ItemsSource
            get { return (IEnumerable)GetValue(ItemsSourceProperty); }
            set { SetValue(ItemsSourceProperty, value); }

One Reply to “Xamarin.Forms – Implementing ItemsSource for Custom Control”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: