【问题标题】:Xamarin Forms MVVM set picker SelectedItem to a valueXamarin Forms MVVM 将选取器 SelectedItem 设置为一个值
【发布时间】:2022-01-07 10:19:43
【问题描述】:

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

任何帮助将不胜感激。

【问题讨论】:

  • 您需要在MaritalStatusList 的数据库中查找值并将SelectedMaritalStatus 设置为该值。 SelectedItem 必须是 ItemsSource 中的值之一
  • 嗨杰森。感谢您的快速答复。我将代码更改为: SelectedMaritalStatus = new KeyValuePair() { Key = 1, Value = details.MaritalStatus };现在我可以看到 set 被调用并且值设置正确,但 UI 没有使用新值更新。知道为什么吗?
  • 因为您将SelectedMaritalStatus 设置为新实例,而不是MaritalStatusList 中已存在的实例之一
  • 嗨杰森。你能根据我的代码结构给我一个例子吗?谢谢。

标签: xamarin.forms mvvm picker


【解决方案1】:

您可以尝试设置 Xamarin Picker 的默认值。您只需在yourpage.xaml.cs 中设置您的选择器的selectedIndex(索引的第一个数字为0),如下所示:

maritalStatus.SelectedIndex=1;

整个代码是:

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

        maritalStatus.SelectedIndex = 1;
    }

// other code
}

注意:

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

【讨论】:

    【解决方案2】:

    SelectedMaritalStatus 必须是MaritalStatusList 中的对象之一

    SelectedMaritalStatus = MaritalStatusList[0];
    

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

    【讨论】:

    • 非常感谢杰森。这解决了我的问题。
    猜你喜欢
    • 2018-04-02
    • 1970-01-01
    • 2018-03-10
    • 2021-06-29
    • 2017-11-16
    • 1970-01-01
    • 2019-11-23
    • 2019-01-25
    • 2020-11-21
    相关资源
    最近更新 更多