summaryrefslogtreecommitdiff
path: root/Xamarin.Forms.Core/Picker.cs
blob: 733f2079f8dd7cba71dc403851e9a848c52522ed (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using Xamarin.Forms.Platform;

namespace Xamarin.Forms
{
	[RenderWith(typeof(_PickerRenderer))]
	public class Picker : View
	{
		public static readonly BindableProperty TitleProperty = BindableProperty.Create("Title", typeof(string), typeof(Picker), default(string));

		public static readonly BindableProperty SelectedIndexProperty = BindableProperty.Create("SelectedIndex", typeof(int), typeof(Picker), -1, BindingMode.TwoWay,
			propertyChanged: (bindable, oldvalue, newvalue) =>
			{
				EventHandler eh = ((Picker)bindable).SelectedIndexChanged;
				if (eh != null)
					eh(bindable, EventArgs.Empty);
			}, coerceValue: CoerceSelectedIndex);

		public Picker()
		{
			Items = new ObservableList<string>();
			((ObservableList<string>)Items).CollectionChanged += OnItemsCollectionChanged;
		}

		public IList<string> Items { get; }

		public int SelectedIndex
		{
			get { return (int)GetValue(SelectedIndexProperty); }
			set { SetValue(SelectedIndexProperty, value); }
		}

		public string Title
		{
			get { return (string)GetValue(TitleProperty); }
			set { SetValue(TitleProperty, value); }
		}

		public event EventHandler SelectedIndexChanged;

		static object CoerceSelectedIndex(BindableObject bindable, object value)
		{
			var picker = (Picker)bindable;
			return picker.Items == null ? -1 : ((int)value).Clamp(-1, picker.Items.Count - 1);
		}

		void OnItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
		{
			SelectedIndex = SelectedIndex.Clamp(-1, Items.Count - 1);
		}
	}
}