Skip to content

Instantly share code, notes, and snippets.

@thunsaker
Created May 26, 2015 21:23
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 thunsaker/1efdc04a4889d1b1009b to your computer and use it in GitHub Desktop.
Save thunsaker/1efdc04a4889d1b1009b to your computer and use it in GitHub Desktop.
Xamarin.Forms BindablePicker
// via https://forums.xamarin.com/discussion/19079/data-binding-for-the-items-source-of-a-picker-control
using System;
using System.Collections;
using Xamarin.Forms;
public class BindablePicker : Picker {
public BindablePicker() {
this.SelectedIndexChanged += OnSelectedIndexChanged;
}
public static BindableProperty ItemsSourceProperty =
BindableProperty.Create<BindablePicker, IEnumerable>(o => o.ItemsSource, default(IEnumerable), propertyChanged: OnItemsSourceChanged);
public static BindableProperty SelectedItemProperty =
BindableProperty.Create<BindablePicker, object>(o => o.SelectedItem, default(object), propertyChanged: OnSelectedItemChanged);
public IEnumerable ItemsSource {
get { return (IEnumerable)GetValue(ItemsSourceProperty); }
set { SetValue(ItemsSourceProperty, value); }
}
public object SelectedItem {
get { return (object)GetValue(SelectedItemProperty); }
set { SetValue(SelectedItemProperty, value); }
}
private static void OnItemsSourceChanged(BindableObject bindable, IEnumerable oldvalue, IEnumerable newvalue) {
var picker = bindable as BindablePicker;
picker.Items.Clear();
if (newvalue != null) {
//now it works like "subscribe once" but you can improve
foreach (var item in newvalue) {
picker.Items.Add(item.ToString());
}
}
}
private void OnSelectedIndexChanged(object sender, EventArgs eventArgs) {
if (SelectedIndex < 0 || SelectedIndex > Items.Count - 1) {
SelectedItem = null;
} else {
SelectedItem = Items[SelectedIndex];
}
}
private static void OnSelectedItemChanged(BindableObject bindable, object oldvalue, object newvalue) {
var picker = bindable as BindablePicker;
if (newvalue != null) {
picker.SelectedIndex = picker.Items.IndexOf(newvalue.ToString());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment