Reputation: 20997
Inside my Xamarin application I have added a Picker control to a page. The setup of that Picker looks like this in xaml
:
<controls:ExtendedPicker x:Name="GenderPicker" Style="{StaticResource PickerControl}" Margin="0,0,0,20"
ItemsSource="{Binding GenderItems}"
ItemDisplayBinding="{Binding Name}"
SelectedItem="{Binding Gender, Mode=TwoWay}" />
In my ViewModel I have this code to populate the picker with some values:
public class GenderItem
{
public string Name { get; set; }
}
public class RegisterViewModel : BaseViewModel
{
private DateTime _birthdate;
public DateTime Birthdate { get => _birthdate; set => SetProperty(ref _birthdate, value); }
public GenderItem Gender { get => _gender; set => SetProperty(ref _gender, value); }
public List<GenderItem> GenderItems { get; set; } = new List<GenderItem>
{
new GenderItem { Naam = "Male" },
new GenderItem { Naam = "Female" },
new GenderItem { Naam = "Confused" }
};
public RegisterViewModel()
{
// This doesn't work
Gender = new GenderItem { Naam = "Female" };
// This works
Birthdate = DateTime.Today.AddYears(-40);
}
}
From within the constructor
I try to set a default selected value for the Picker
control. But for some reason the value isn't selected in the Picker
.
I also set a datetime
property with a value and I do see that this value is picked up by the Date control.
Why isn't this working for the Picker
control? What can I do to make this work?
The SetProperty
method lives inside my BaseViewModel
class. You get this with every new Xamarin project.
public class BaseViewModel : INotifyPropertyChanged
{
public IDataStore<Item> DataStore => DependencyService.Get<IDataStore<Item>>();
bool _isBusy = false;
public bool IsBusy
{
get => _isBusy;
set => SetProperty(ref _isBusy, value);
}
string _title = string.Empty;
public string Title
{
get => _title;
set => SetProperty(ref _title, value);
}
protected bool SetProperty<T>(ref T backingStore, T value,
[CallerMemberName] string propertyName = "",
Action onChanged = null)
{
if (EqualityComparer<T>.Default.Equals(backingStore, value))
return false;
backingStore = value;
onChanged?.Invoke();
OnPropertyChanged(propertyName);
return true;
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
var changed = PropertyChanged;
if (changed == null)
return;
changed.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
Upvotes: 0
Views: 235
Reputation: 89082
Gender
needs to be an element in GenderItems
. Right now you are creating a new object that has the same value as an item in GenderItems
, but it is not the same object
Upvotes: 1