I have a picker inside a CollectionView that should select a predefined item ColorNav
but when it starts the item is not selected.
XAML:
<StackLayout>
<Label Text="Players" />
<CollectionView ItemsSource="{Binding PlayerList}">
<CollectionView.ItemTemplate>
<DataTemplate x:DataType="model:Player">
<SwipeView>
<Border>
<Grid ColumnDefinitions="*, *, *" ColumnSpacing="1" >
<Label Grid.Column="0" Text="{Binding Name}" />
<Picker Grid.Column="1" ItemsSource="{Binding ColorsPicker, Source={RelativeSource AncestorType={x:Type viewmodel:MainViewModel}}}" ItemDisplayBinding="{Binding Name}" SelectedItem="{Binding ColorNav}"/>
<Label Grid.Column="2" Text="{Binding ColorNav.Name}"/>
</Grid>
</Border>
</SwipeView>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
<Button Text="Save" Command="{Binding SaveCommand}"/>
</StackLayout>
C#
public class Player
{
public string Name { get; set; } = default!;
public int ColorId { get; set; } = default!;
public Colour ColorNav { get; set; } = default!;
}
public class Colour
{
public int ColorId { get; set; }
public string Name { get; set; } = default!;
}
While debugging, I can see that ColorNav is loaded in the BindingContext, but somehow it becomes null when the page starts. When I go to ‘Save, ColorNav
is null for every player. If I remove SelectedItem="{Binding ColorNav}"
from the Picker, ColorNav remains as expected.
luis_m is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.