Created
July 17, 2014 19:26
-
-
Save hjerpbakk/286cfbdd5dfd379a9155 to your computer and use it in GitHub Desktop.
A Picker-control for Xamarin.Forms which enables data binding through an ItemsSource and the SelectedItem.
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
using System; | |
using Xamarin.Forms; | |
using System.Collections; | |
namespace YourNamespace.Views.Controls { | |
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
Hi guys,
I have a problem when I try to bind. The error is:
I can't understand why.
Thank you in advance,