Xamarin Forms MVVM 将选择器 SelectedItem 设置为一个值

Xamarin Forms MVVM set picker SelectedItem to a value

我是 Xamarin.Forms 和 MVVM 的新手。我在 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>

这是我设置项目来源的方式:

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"}

        };
    }
}

这就是我设置 属性 的方式:

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);
        }
    }

以上正确显示了选择器中的列表。我的问题是我有一个表单,我想将选择器设置为来自数据库的值。我还有一些其他条目可以从 ViewModel 中成功设置,如下所示:

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
        }

只有婚姻状况选择器我无法设置,其他都可以。

*** 更新 ***

这是我的 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));
    }

如有任何帮助,我们将不胜感激。

您可以尝试设置 Xamarin 的默认值 Picker。你只要在yourpage.xaml.cs中设置你的picker的selectedIndex(index的第一个数字是0)就可以了:

maritalStatus.SelectedIndex=1;

整个代码为:

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

        maritalStatus.SelectedIndex = 1;
    }

// other code
}

注:

我建议您重命名您的选择器以更好地识别您的选择器(例如 mStatusPicker

SelectedMaritalStatus 必须是 MaritalStatusList

中的对象之一
SelectedMaritalStatus = MaritalStatusList[0];

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