Reputation: 891
I've got a picker on the screen, that has an initial value, as well as the option to change the item in the picker.
While my selectedItem is set, I don't see that on the picker on the screen, the picker has no value set, and it's not until I select a value, that it actually displays something in the picker on the screen (At this time the SelectedItem is also updated with the new value).
My xaml:
<Picker
ItemsSource="{Binding FeedbackTypes}"
SelectedItem="{Binding SelectedFeedbackType, Mode=TwoWay}"
ItemDisplayBinding="{Binding Name}">
</Picker>
My ViewModel properties:
private ValueName _selectedFeedbackType;
public ValueName SelectedFeedbackType
{
get { return _selectedFeedbackType; }
set
{
_selectedFeedbackType = value;
OnPropertyChanged(nameof(SelectedFeedbackType));
}
}
public ObservableCollection<ValueName> FeedbackTypes
{
get
{
var feedbackTypes = new ObservableCollection<ValueName>();
foreach (FeedbackType feedback in
Enum.GetValues(typeof(FeedbackType)))
{
feedbackTypes.Add(new ValueName
{
Value = feedback,
Name = feedback.ToName()
});
}
return feedbackTypes;
}
}
And in my ViewModel constructor I've got:
SelectedFeedbackType = new ValueName { Value = feedbackType, Name = feedbackType.ToName() };
The constructor works sets the SelectedFeedbackType correctly and if I don't make any changes to the picker, that is the value I get in there on submit, however, I do not see that value in the picker by default. The picker is empty until a selection is made.
I've also tried to bind the SelectedIndex value to the SelectedFeedbackType, however that one will not show the initially selected value either in the picker.
Upvotes: 1
Views: 2927
Reputation: 9234
You could try to set defalut value of the Xamarin Picker
.
You just set the selectedIndex(the first number of index is 0) of your picker like the following code.
Mypicker.SelectedIndex=1;
There is a code of demo.
GIF of demo when first running.
You can download this demo by the link. https://developer.xamarin.com/samples/xamarin-forms/UserInterface/PickerDemo/
Then changed the code of MonkeysPage.xaml
.
<Picker x:Name="Mypicker" Title="Baboon" ItemsSource="{Binding Monkeys}" ItemDisplayBinding="{Binding Name}" SelectedItem="{Binding SelectedMonkey}" />
Add the defaule value of Picker
in MonkeysPage.xaml.cs
.
public MonkeysPage()
{
InitializeComponent();
BindingContext = new MonkeysPageViewModel();
Mypicker.SelectedIndex=1;
}
}
Upvotes: 1