简体   繁体   中英

Xamarin Forms Using multiple lists in ViewModel

I have a problem. I created a CollectionView with a ViewModel, in that ViewModel I have 2 different Lists. Now I know how to show data from 1 list, but now I want in the datatemplate a picker with the data of the second list. Here is the xaml code:

<CollectionView ItemsSource="{Binding imageList}">
    <CollectionView.ItemsLayout>
        <GridItemsLayout Orientation="Vertical" />
    </CollectionView.ItemsLayout>
    <CollectionView.ItemTemplate>
        <DataTemplate>

            <Picker Grid.Row="0" Grid.RowSpan="2" Grid.Column="3" Title="Formaat" ItemsSource="{Binding secondList}" HorizontalOptions="FillAndExpand" />

            <Label Grid.Row="0" Grid.Column="4" VerticalTextAlignment="Center" VerticalOptions="Center"  
                    HorizontalOptions="Center" Text="{Binding Price, StringFormat='€ {0:F2}'}" TextColor="Black"
                    FontSize="18" />
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

So the Price does get shown from the imageList, but the Picker is empty. In the Picker I want the element Name from the secondList

How can I fix this?

The problem is that your BindingContext in the DataTemplate of your CollectionView element is an item from your imageList . Therefore the binding will not work, as I assume your secondList is not a part of the element's model that you're using in the imageList but rather a part of the entire view model used for the page.

I would suggest using the RelativeBinding . I don't know the names of your models but your Picker binding could look like this:

<Picker ItemsSource="{Binding Source={RelativeSource AncestorType={x:Type local:YourViewModelTypeName}}, Path=secondList}" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM