Created
May 26, 2015 21:23
-
-
Save thunsaker/1efdc04a4889d1b1009b to your computer and use it in GitHub Desktop.
Xamarin.Forms BindablePicker
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
// 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