Created
April 21, 2017 15:24
-
-
Save julesx/5b04b9ed170b07cb8bef98a00acb7bfc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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