NickUK77
NickUK77

Reputation: 23

Xamarin Forms MVVM set picker SelectedItem to a value

I am new to Xamarin.Forms and MVVM. I have following picker in XAML:

<Picker Title="Marital Status"
                        x:Name="maritalStatus"
                        Margin="10,5,10,0"
                        ItemsSource="{Binding MaritalStatusList}"
                        ItemDisplayBinding="{Binding Value}" 
                        SelectedItem="{Binding SelectedMaritalStatus, Mode=TwoWay}">
                </Picker>

This is how I setup the item source:

public class KeyValuePair
{
    public int Key { get; set; }
    public string Value { get; set; }
}

public static class MaritalStatus
{
    public static List<KeyValuePair> GetMaritalStatus()
    {
        return new List<KeyValuePair>()
        {
            new KeyValuePair() {Key=1, Value="Single"},
            new KeyValuePair() {Key=1, Value="Married"},
            new KeyValuePair() {Key=1, Value="Widowed"},
            new KeyValuePair() {Key=1, Value="Divorced"},
            new KeyValuePair() {Key=1, Value="Civil Partnership"}

        };
    }
}

And this is how I set the property:

KeyValuePair selectedMaritalStatus;
    public KeyValuePair SelectedMaritalStatus
    {
        get => selectedMaritalStatus;
        set
        {
            SetProperty(ref selectedMaritalStatus, value);
            MaritalStatusText = selectedMaritalStatus.Value;
        }
    }

    string maritalStatusText;
    public string MaritalStatusText
    {
        get => maritalStatusText;
        set
        {
            SetProperty(ref maritalStatusText, value);
        }
    }

The above displays properly the list in the picker. My problem is that I have a form and I want to set the picker to the value that comes from a database. I have some other entries that I can successfully set from a ViewModel like so:

foreach (EmployeeDetails details in EmployeeDetailsService.EmployeeDetails)
        {
            Id = details.Id;
            ADEmployeeID = await new MSGraphService().GetUserIdAsync();
            FirstName = details.FirstName;
            MiddleName = details.MiddleName;
            LastName = details.LastName;
            Street = details.Address.Street;
            Block = details.Address.Block;
            City = details.Address.City;
            County = details.Address.County;
            PostCode = details.Address.PostCode;
            Telephone = details.Telephone;
            DateOfBirth = details.DateOfBirth != null ? DateTime.Parse(details.DateOfBirth) : DateTime.Now.Date;
            CountryOfBirth = details.CountryOfBirth;
            SelectedMaritalStatus.Value = details.MaritalStatus;
            //MaritalStatusText = details.MaritalStatus;
            PassportIssuingCountry = details.PassportIssuingCountry;
            PassportNumber = details.PassportNumber;
            PassportExpiryDate = details.PassportExpiryDate != null ? DateTime.Parse(details.PassportExpiryDate) : DateTime.Now.Date;
            BankName = details.BankName;
            BankAddress = details.BankAddress;
            BankSortCode = details.BankSortCode;
            NationalInsuranceNumber = details.NationalInsuranceNumber;
            //    //! Need to add P45
        }

Marital Status picker is the only one that I cannot set, everything else works.

*** UPDATE ***

This is my SetProperty:

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 = "")
    {
        PropertyChangedEventHandler changed = PropertyChanged;
        if (changed == null) { return; }

        changed.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

Any help would be much appreciated.

Upvotes: 1

Views: 1759

Answers (2)

Jason
Jason

Reputation: 89082

SelectedMaritalStatus has to be one of the objects in MaritalStatusList

SelectedMaritalStatus = MaritalStatusList[0];

or

SelectedMaritalStatus = MaritalStatusList.First(x => x.ID == "some value from your db");

Upvotes: 2

Jessie Zhang -MSFT
Jessie Zhang -MSFT

Reputation: 13813

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 in yourpage.xaml.cs just as follows:

maritalStatus.SelectedIndex=1;

The whole code is:

   public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();

        maritalStatus.SelectedIndex = 1;
    }

// other code
}

Note:

I suggest you rename your Picker to better indentify your Picker(e.g. mStatusPicker)

Upvotes: 0

Related Questions