Skip to content

Instantly share code, notes, and snippets.

@julesx
Created April 21, 2017 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save julesx/5b04b9ed170b07cb8bef98a00acb7bfc to your computer and use it in GitHub Desktop.
Save julesx/5b04b9ed170b07cb8bef98a00acb7bfc to your computer and use it in GitHub Desktop.
public class RepeaterView : StackLayout
{
public static readonly BindableProperty ItemTemplateProperty =
BindableProperty.Create("ItemTemplate", typeof(DataTemplate), typeof(RepeaterView));
public static readonly BindableProperty ItemsSourceProperty =
BindableProperty.Create("ItemsSource", typeof(IEnumerable), typeof(RepeaterView), Enumerable.Empty<object>(), BindingMode.OneWay, null, ItemsChanged);
public IEnumerable ItemsSource
{
get { return (IEnumerable)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
public DataTemplate ItemTemplate
{
get { return (DataTemplate)GetValue(ItemTemplateProperty); }
set { SetValue(ItemTemplateProperty, value); }
}
private static void ItemsChanged(BindableObject bindable, object oldvalue, object newvalue)
{
var repeater = (RepeaterView)bindable;
repeater.Children.Clear();
var collection = newvalue as INotifyCollectionChanged;
if (collection != null)
{
collection.CollectionChanged += (sender, args) =>
{
foreach (string newItem in args.NewItems)
AddChildView(newItem, repeater);
};
}
foreach (var viewModel in (IEnumerable)newvalue)
{
AddChildView(viewModel, repeater);
}
}
private static void AddChildView(object viewModel, RepeaterView repeater)
{
var content = repeater.ItemTemplate.CreateContent();
if (!(content is View) && !(content is ViewCell))
{
throw new Exception(nameof(content) + " - Invalid visual object: " + content.GetType());
}
var view = (content is View) ? content as View : ((ViewCell)content).View;
view.BindingContext = viewModel;
repeater.Children.Add(view);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment