In a custom component, I define a bindable property of ARRAY type:
public static BindableProperty LabelsProperty = BindableProperty.Create(nameof(LabelStrings), typeof(string[]), typeof(BLSelector), null, BindingMode.Default, propertyChanged: OnLabelsPropertyChanged);
public string[] LabelStrings
{
get => (string[])GetValue(LabelsProperty);
set => SetValue(LabelsProperty, value);
}
private static void OnLabelsPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
var current = bindable as BLSelector;
// Check the number of strings
if (current.Commands != null && current.LabelStrings.Count() != current.Commands.Count())
{
Debug.WriteLine("Component::BLSelector - Bad number of Labels");
throw new TargetParameterCountException();
}
// Updates the number of Label Controls
current.LabelControls = new Label[current.LabelStrings.Count()];
// Set up the layout
current.GridContendUpdate();
}
I would like to use this component from XAML file and thus set this property like this :
<components:BLSelector>
<components:BLSelector.LabelStrings>
<x:Array Type="{x:Type x:String}">
<x:String>" Activités "</x:String>
<x:String>" Prestations "</x:String>
</x:Array>
</components:BLSelector.LabelStrings>
</components:BLSelector>
The app crashes without message (due to a null reference?) when I launch it. If a put a breakpoint on the setter, I can see that it is never called.
BUT ... If I add one "internal" initialisation in the constructor of the component like the following, the setter is callled two times (from the internal declaration and with the data of the XAML file - which is normal) and the app do not crash.
public BLSelector()
{
InitializeComponent();
LabelStrings = new string[2]{ "Test 1", "Test 2" };
}
Why does the App crash if I only assign the property to the Array defined in the XAML file ?
What is the real type of array in XAML ? Is there an initialisation problem ? Any idea ?
Thanks a lot for your suggestions
The naming convention for bindable properties is that the bindable property identifier must match the property name specified in the
Create
method, with "Property" appended to it. So try to change your bindable property name:
public static BindableProperty LabelStringsProperty = BindableProperty.Create(nameof(LabelStrings), typeof(string[]), typeof(BLSelector), null, BindingMode.Default, propertyChanged: OnLabelsPropertyChanged);