简体   繁体   中英

Xamarin Forms - ListView Selection Issue

I have a basic ListView here:

<ListView x:Name="productsListView"
                      HasUnevenRows="True"                       
                        VerticalOptions="FillAndExpand"
                      SeparatorVisibility="None"
                      ItemSelected="OnItemSelected">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <ViewCell.View>
                                <Frame HasShadow="True" Padding="20" Margin="20">
                                    <StackLayout>
                                        <Image Source="{Binding featured_src}"/>
                                        <Label Text="{Binding title}" FontSize="Medium"/>
                                        <Frame BackgroundColor="Red" Padding="5" HorizontalOptions="Center" WidthRequest="80" HeightRequest="20" CornerRadius="00">
                                            <Label WidthRequest="40" Text="{Binding price , StringFormat='${0}'}" TextColor="White" HorizontalTextAlignment="Center"></Label>
                                        </Frame>
                                    </StackLayout>
                                </Frame>
                            </ViewCell.View>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

When I select an item, I want to pass the product selected to another page "ProductDetailPage".

async void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            var item = (Product)e.SelectedItem;
            await Navigation.PushAsync(new ProductDetailPage(item));
        }

The problem is that it seems to carry over the entire history of selection. For example here's a few test cases:

Selection: Apple - Output: Apple Selection: Pear - Output: Apple, Apple, Pear Selection: Grape - Output: Apple, Apple, Pear, Grape

Hope that makes sense.

I also tried clearing the selection but when it clears, it shows a blank page.

((ListView)sender).SelectedItem = null;

Hope you have a solution for this.

I was able to fix the issue. If anyone wants to know, you need to store the selected product details inside a global variable and when you add the item to cart, simply retrieve the selected product variable.

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