Xamarin.Forms: Picker control and "Items" binding problem...
If I tell you "ComboBox", you will see quickly of which control I'm talking about. There no control named "ComboBox" in Xamarin.Forms but if you search a little, you will find the "Picker" control.
Class: Xamarin.Forms.Picker
In the namespace: Xamarin.Forms
Doc link: http://iosapi.xamarin.com/index.aspx?link=T%3AXamarin.Forms.Picker
The problem is that you cannot bind directly "Picker.Items" property in the XAML file ! For that you have to use the code behind file.
xaml (doesn't work):
<Picker Items="{Binding MyViewModelList}"... />
So what do we have to do ?
1- Name your "Picker" control in the xaml file (by adding an attribute like x:Name="uiPicker")
2- On the parent page in code behind, override the "OnBindingContextChanged( )" method
3- In this method, fill your "Picker.Items" property from your viewmodel's values.
4- On the XAML file, you can only bind the property "SelectedIndex" --> so thanks to this index (in your ViewModel), you will be able to get back your selected value.
xaml:
<Picker SelectedIndex="{Binding MyValueIndex}"... />
Code behind:
Note: If your list is dynamic (like an ObservableCollection), you will have to manage the "CollectionChanged" events to update your picker Items !
Class: Xamarin.Forms.Picker
In the namespace: Xamarin.Forms
Doc link: http://iosapi.xamarin.com/index.aspx?link=T%3AXamarin.Forms.Picker
The problem is that you cannot bind directly "Picker.Items" property in the XAML file ! For that you have to use the code behind file.
xaml (doesn't work):
<Picker Items="{Binding MyViewModelList}"... />
So what do we have to do ?
1- Name your "Picker" control in the xaml file (by adding an attribute like x:Name="uiPicker")
2- On the parent page in code behind, override the "OnBindingContextChanged( )" method
3- In this method, fill your "Picker.Items" property from your viewmodel's values.
4- On the XAML file, you can only bind the property "SelectedIndex" --> so thanks to this index (in your ViewModel), you will be able to get back your selected value.
xaml:
<Picker SelectedIndex="{Binding MyValueIndex}"... />
Code behind:
protected override void OnBindingContextChanged() { base.OnBindingContextChanged(); MyViewModel vm = BindingContext as MyViewModel; if (vm != null) { this.uiPicker.Items.Clear(); foreach (var it in vm.MyViewModelList) { thePicker.Items.Add(it); } } }
Note: If your list is dynamic (like an ObservableCollection), you will have to manage the "CollectionChanged" events to update your picker Items !
You can also use a custom "Bindable Picker control",
ReplyDeletethat implements "ItemsSource" & "SelectedItem" properties !
Code found on Xamarin blog:
https://forums.xamarin.com/discussion/30801/xamarin-forms-bindable-picker
Example of use: