I got an issue when trying to create a custom control with a picker inside. I create a bindable property
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);
}
Then I populate my picker and set the value that I want to show first in the constructor of my control :
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);
And after this I call my control like that :
<controls:PhoneEntry
Margin="0,8,0,0"
PhoneCode="{Binding CurrentIndex}"
PhoneNumber="{Binding CurrentPhoneNumber}"
ValidPhoneNumber="{Binding ValidPhoneNumber}" />
My picker is set OK, I can see it with any problem in my UI, but I don't get any value in my viewmodel until the user change the value of the picker
Does anyone know why ? Thanks in advance !
CodePudding user response:
I think my problem is solved and it was the binding mode that cause my issue. I set it to onewaytosource and then it was ok
CodePudding user response:
you want to set a default value for a bindableproperty. you must set it to defaultValueCreator parameter.
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);
}