A. Vreeswijk
A. Vreeswijk

Reputation: 954

Xamarin Forms Access parent collection item

I have a problem. I have a CollectionView with a List<Album> albumList with inside an Album a List<Picture> Pictures. Now I created the following XAML:

<CollectionView ItemsSource="{Binding albumList}">
    <CollectionView.ItemsLayout>
        <GridItemsLayout Orientation="Vertical" />
    </CollectionView.ItemsLayout>
    <CollectionView.ItemTemplate>
        <DataTemplate>
            <Grid VerticalOptions="Center">
                <Grid.RowDefinitions>
                    <RowDefinition Height="50"/>
                    <RowDefinition Height="90"/>
                    <RowDefinition Height="5"/>
                    <RowDefinition Height="Auto"/>
                    <RowDefinition Height="30"/>
                    <RowDefinition Height="10"/>
                </Grid.RowDefinitions>

                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="3"/>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="3"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="3"/>
                </Grid.ColumnDefinitions>

                <StackLayout Grid.Row="3" Grid.Column="3" Grid.ColumnSpan="2" Padding="0" Margin="0"
                             BindableLayout.ItemsSource="{Binding Pictures}" Orientation="Vertical">
                    <BindableLayout.ItemTemplate>
                        <DataTemplate>
                            <StackLayout Orientation="Horizontal">
                                <Label Grid.Column="1" Text="{Binding albumList.Price, StringFormat='€ {0:F2}'}" TextColor="Black" FontSize="16" />
                            </StackLayout>
                        </DataTemplate>
                    </BindableLayout.ItemTemplate>
                </StackLayout>
            </Grid>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

Now I want to access the current Album.Price inside the following line: <Label Grid.Column="1" Text="{Binding albumList.Price, StringFormat='€ {0:F2}'}" TextColor="Black" FontSize="16" />

This is outside the current binding of Pictures, so how can I enter a value from outside the current Binding?

Upvotes: 0

Views: 777

Answers (1)

Ricardo Dias Morais
Ricardo Dias Morais

Reputation: 2087

You can define the BindingContext from a reference of an element outside the nested Collection, give a name to your StackLayout for example:

<StackLayout x:Name="ElementForReference" Grid.Row="3" Grid.Column="3" Grid.ColumnSpan="2" Padding="0" Margin="0"
                         BindableLayout.ItemsSource="{Binding Pictures}" Orientation="Vertical">

And then define the BindingContext with the reference of the element outside the nested one:

{Binding BindingContext.Price, Source={x:Reference Name=ElementForReference}}

Upvotes: 2

Related Questions