问题
Hoping you can advise as I've tried all methods to bind a picker in a Listview to my item source values using both code-behind and MVVM. The picker binding works outside of the ListView, but not inside - is this out of the box or just not possible?
Please see my list below!
code
<ListView
x:Name="TypesList"
HeightRequest="53"
BackgroundColor="White"
IsGroupingEnabled="True"
IsPullToRefreshEnabled="false"
ItemsSource="{Binding Items}"
IsRefreshing="{Binding IsBusy}"
RefreshCommand="{Binding LoadTypesCommand}"
SeparatorVisibility="None"
>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell Height="63">
<StackLayout Orientation="Horizontal" VerticalOptions="Center">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="150"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="250"/>
<ColumnDefinition Width="60"/>
<ColumnDefinition Width="70"/>
</Grid.ColumnDefinitions>
<!-- -->
<Label Grid.Column="0"
Grid.Row="0"
VerticalOptions="Center"
FontAttributes="None"
Text="{Binding .Name, Mode=TwoWay} "
TextColor="Black"
VerticalTextAlignment="Center"
Margin="0,15,0,110"
BackgroundColor="White"
Padding="20,10,0,10"
FontFamily="Hiragino Sans"
FontSize="14"
HeightRequest="53"
x:Name="userLabel"
/>
<Entry Grid.Column="1"
Grid.Row="0"
Text="{Binding .Amount, Mode=TwoWay}"
TextColor="Black"
VerticalOptions="EndAndExpand"
Margin="0,15,20,110"
BackgroundColor="White"
FontFamily="Hiragino Sans"
FontSize="14"
HeightRequest="40"
WidthRequest="55"
x:Name="userEntry"
/>
<Picker Grid.Column="2"
Grid.Row="0"
x:Name="mPicker"
ItemsSource="{Binding UserOptions}"
/>
</Grid>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
code
Code behind
code mPicker.ItemsSource = ViewModel.UserOptions; code
The model allocates UserOptions and this works for a picker outside the listview so I don't believe there is anything wrong with the model or this code needs to be posted.
Any help appreciated!
回答1:
List view has its own binding context. So you need to get binding context of view model and then bind to picker like this
Set a name of your view like this
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Name="viewName">
<Picker Grid.Column="2"
Grid.Row="0"
x:Name="mPicker"
ItemsSource="{Binding BindingContext.UserOptions, Source={x:Reference viewName}}"
/>
来源:https://stackoverflow.com/questions/65672124/picker-itemsource-values-not-binding-in-a-xaml-listview