自定义控件选择器可绑定所选项目在初始化时不起作用

Custom control picker bindable selected item don't work at the initialisation

我在尝试创建内部带有选取器的自定义控件时遇到问题。 我创建了一个可绑定的 属性

public static readonly BindableProperty PhoneCodeProperty = BindableProperty.Create(nameof(PhoneCode),
            typeof(PhoneIndex),
            typeof(PhoneEntry),
            defaultBindingMode: BindingMode.TwoWay,
            propertyChanged: PhoneCodePropertyChanged);

private static void PhoneCodePropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
      PhoneEntry control = (PhoneEntry)bindable;

      control.Picker.SelectedItem = newValue ?? oldValue;
      Console.WriteLine($"Picker Value => {control.Picker.SelectedItem}");

}

public PhoneIndex PhoneCode
{
      get => (PhoneIndex)GetValue(PhoneCodeProperty);

      set => SetValue(PhoneCodeProperty, value);
}

然后我填充我的选择器并设置我想在我的控件的构造函数中首先显示的值:

phoneNumberUtil = PhoneNumberUtil.GetInstance();
var callingcode = phoneNumberUtil.GetSupportedRegions();


PhoneCodesStrings = new List<PhoneIndex>();

foreach (string CountryCode in callingcode)
{
      PhoneCodesStrings.Add(new PhoneIndex(CountryCode, phoneNumberUtil.GetCountryCodeForRegion(CountryCode)));
}

PhoneCodesStrings.Sort(CompareByCountryCode);
Picker.ItemsSource = PhoneCodesStrings;
Predicate<PhoneIndex> predicate = IsFr;

Picker.SelectedIndexChanged += Picker_SelectedIndexChanged;
Entry.TextChanged += Entry_TextChanged;

PhoneCode = PhoneCodesStrings.Find(predicate);

然后我这样调用我的控件:

<controls:PhoneEntry
                    Margin="0,8,0,0"
                    PhoneCode="{Binding CurrentIndex}"
                    PhoneNumber="{Binding CurrentPhoneNumber}"
                    ValidPhoneNumber="{Binding ValidPhoneNumber}" />

我的选择器设置正常,我可以在我的 UI 中看到它有任何问题,但是在用户更改选择器的值之前我没有在我的视图模型中获得任何值

有谁知道为什么?提前致谢!

我想我的问题已经解决了,是绑定模式导致了我的问题。我设置成onewaytosource然后就ok了

您想为可绑定属性设置默认值。 您必须将其设置为 defaultValueCreator 参数。

public static readonly BindableProperty PhoneCodeProperty = BindableProperty.Create(nameof(PhoneCode),
            typeof(PhoneIndex),
            typeof(PhoneEntry),
            defaultBindingMode: BindingMode.TwoWay,
            propertyChanged: PhoneCodePropertyChanged
            defaultValueCreator: PhoneCodeDefaultValue);

public static PhoneIndex PhoneCodeDefaultValue(BindableObject bindable)
{
           PhoneCodesStrings = new List<PhoneIndex>();

           foreach (string CountryCode in callingcode)
           {
                PhoneCodesStrings.Add(new PhoneIndex(CountryCode,phoneNumberUtil.GetCountryCodeForRegion(CountryCode)));
           }
           Predicate<PhoneIndex> predicate = IsFr;
           return PhoneCodesStrings.Find(predicate);
 }