Binding to a calculated property of a BindableProperty from code behind

53 views Asked by At

In short, I have a custom control in Xamarin for which I defined a BindableProperty, which I would like to bind to the control's xaml via a calculated property in the code behind, but it always displays as null because the calculated property is evaluated when the BindableProperty didn't have a value yet, and afterward I am missing property changed notification logic. Which is the right way to do it?

Long explanation for context:

I am writing a custom control in Xamarin (which I named TabbedLayout). I intend to bind an array of Views to a BindableProperty of the control, like so:

<controls:TabbedLayout.TabContents>
  <x:Array Type="{x:Type View}">
    <Button Text="Hello world 1!"/>
    <Button Text="Hello world 2!"/>
    <Button Text="Hello world 3!"/>
    <Button Text="Hello world 4!"/>
    <Button Text="Hello world 5!"/>
  </x:Array>
</controls:TabbedLayout.TabContents>

To that effect I have defined a BindableProperty in the code behind the Control (TabbedLayout.xaml.cs):

public static readonly BindableProperty TabContentsProperty = BindableProperty.Create(
    nameof(TabContents),
    typeof(View[]),
    typeof(TabbedLayout),
    null,
    BindingMode.OneWay);

public View[] TabContents
{
    get => (View[])GetValue(TabContentsProperty);
    set => SetValue(TabContentsProperty, value);
}

However, from the control's xaml I wish to display only one of those Views. I have first defined a int property to control which is the selected index (with other parts of the control, let's assume that int SelectedIndex = 0 and I wish to display the first element).

I have then created a calculated property like so:

public View DisplayedElement = TabContents?.ElementAt(SelectedIndex);

And I have bonded to it from the control's xaml like so:

<ContentView Content="{Binding DisplayedElement, Source={x:Reference TheControl}, Mode=OneWay}"/>

At this point, the ContentView displays empty because TabContents is still null.

From here, how would I update the view as soon as the BindableProperty value is set, the first time and every time it might be modified, to trigger a refresh of the bound DisplayedElement property?

0

There are 0 answers