Search code examples
xamarinbindingxamarin.formsitemssource

ItemsSource bindable property


I'm trying to make ContentView with 2 items (Label and DatePicker) and I need to send ItemsSource for second item as bindable property.

I tried to use BindingBase, but it didn't work.

Xaml:

<Grid>
    <Label
        Text="Text"
        TextColor="Black"
        VerticalOptions="CenterAndExpand" />

    <controls:ExtendedPicker
        Title="Title"
        HorizontalOptions="End"
        ItemDisplayBinding="{Binding PickerItemDisplayBinding, Source={x:Reference This}}"
        ItemsSource="{Binding PickerItemsSource, Source={x:Reference This}}"
        SelectedIndex="{Binding PickerSelectedIndex, Source={x:Reference This}}" />
</Grid>

Xaml.cs:

public static readonly BindableProperty PickerItemsSourceProperty = BindableProperty.Create(
    "PickerItemsSource",
    typeof(IList),
    typeof(DetailedPicker));

public static readonly BindableProperty PickerSelectedIndexProperty = BindableProperty.Create(
    "PickerSelectedIndex",
    typeof(int),
    typeof(DetailedPicker));

public static readonly BindableProperty PickerItemDisplayBindingProperty = BindableProperty.Create(
    "PickerItemDisplayBinding",
    typeof(BindingBase),
    typeof(DetailedPicker));


public IList PickerItemsSource
{
    get => (IList) GetValue(PickerItemsSourceProperty);
    set => SetValue(PickerItemsSourceProperty, value);
}

public int PickerSelectedIndex
{
    get => (int) GetValue(PickerSelectedIndexProperty);
    set => SetValue(PickerSelectedIndexProperty, value);
}

public BindingBase PickerItemDisplayBinding
{
    get => (BindingBase) GetValue(PickerItemDisplayBindingProperty);
    set => SetValue(PickerItemDisplayBindingProperty, value);
}

How can I bind ItemsSource as BindableProperty for ContentView?


Solution

  • I'm not sure you can use x:Reference to the this keyword. I've never heard about such a thing.

    Although I guess you can work around it, by giving a x:Name to your ContentView. Just like this:

    <ContentView xmlns="http://xamarin.com/schemas/2014/forms" 
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:controls="clr-namespace:Your.Controls.Namespace;assembly=packageName"
                 x:Class="Your.Another.Control.Namespace.DetailedPicker"
                 x:Name="MyThisReference">
        <ContentView.Content>
            <Grid>
                <!-- Your label and picker goes here -->
                <!-- ... -->
                             ItemsSource="{Binding PickerItemsSource, Source={x:Reference MyThisReference}}"
                <!-- ... -->
            </Grid>
        </ContentView.Content>
    </ContentView>
    

    I hope it helps.