Share via

collectionView deselection

Eduardo Gomez 4,316 Reputation points
2021-01-06T20:22:21.787+00:00

Hello

I have a little problem with my collection view

<ContentPage.BindingContext>
        <vm:PokeCollectionVM />
    </ContentPage.BindingContext>

    <CollectionView ItemsSource="{x:Binding pokeItems}"
                    SelectionMode="Single"
                    SelectedItem="{x:Binding SelectedItem, Mode=TwoWay}"
                    SelectionChangedCommand="{x:Binding SelectedItemCommand}">
        <CollectionView.EmptyView>
            <Grid>
                <StackLayout VerticalOptions="Center">
                    <Image Source="Load" />
                    <Label Text="Getting data..."
                           FontSize="Large"
                           FontAttributes="Bold"
                           HorizontalOptions="Center"
                           VerticalOptions="Center" />
                </StackLayout>
            </Grid>
        </CollectionView.EmptyView>
        <CollectionView.ItemTemplate>
            <DataTemplate>
                <StackLayout>
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup Name="CommonStates">
                            <VisualState Name="Normal" />
                            <VisualState Name="Selected">
                                <VisualState.Setters>
                                    <Setter Property="BackgroundColor"
                                            Value="#CAC8AF" />
                                </VisualState.Setters>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>
                    <Frame BackgroundColor="#BD0D0D"
                           Margin="10"
                           CornerRadius="20">
                        <StackLayout Orientation="Horizontal">
                            <Image Source="{x:Binding image_url}" />
                            <Label Text="{x:Binding name}"
                                   Margin="5"
                                   FontAttributes="Bold"
                                   TextColor="GhostWhite" />
                        </StackLayout>
                    </Frame>
                </StackLayout>
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>

this is my VM

private ObservableCollection<Result> _pokeItems;
        private Result selectedItem;

        public ObservableCollection<Result> pokeItems {
            get { return _pokeItems; }
            set
            {
                if (_pokeItems != value) {
                    _pokeItems = value;
                    RaisePropertyChanged();
                }
            }
        }

        public ICommand SelectedItemCommand { get; set; }
        public Result SelectedItem {
            get => selectedItem;
            set
            {
                selectedItem = value;
                RaisePropertyChanged();
            }
        }

        public PokeCollectionVM() {

            SelectedItemCommand = new Command(async () => {

                var nav = Application.Current.MainPage;

                await nav.Navigation.PushAsync(new PokeDetailPage(selectedItem));
                selectedItem = null;

            });

            pokeItems = new ObservableCollection<Result>();
            loadData();
        }

        public async void loadData() {

            pokeItems = await PokeServices.getPokemonsAsync();

        }
    }

The problem is that I want to completely deselect the item when I go to the detail page, so I don't see it highlighted when I navigate back. I already set the selectedItem to null, but it is still hightlited when I come back

Developer technologies | .NET | Xamarin
0 comments No comments

1 answer

Sort by: Most helpful
  1. JessieZhang-MSFT 7,721 Reputation points Microsoft External Staff
    2021-01-07T07:08:08.78+00:00

    Hello,

    Welcome to our Microsoft Q&A platform!

    You could try to add event SelectionChanged in your CollectionView.
    Please refer to the following code:

    <CollectionView ItemsSource="{Binding Monkeys}"   
                     x:Name="myCollectionView"  
                    SelectedItem="{Binding SelectedMonkey,Mode=TwoWay}"  
                      
                    SelectionChanged="CollectionView_SelectionChanged"  
                    SelectionMode="Single">  
     <!--    other code-->  
     </CollectionView >  
    

    and add function CollectionView_SelectionChanged in your page:

    private void CollectionView_SelectionChanged(object sender, SelectionChangedEventArgs e)  
    {  
        var view = sender as CollectionView;  
    
        if (view.SelectedItem != null)  
        {  
            UpdateSelectionData(e.PreviousSelection, e.CurrentSelection);  
        }  
    
    }  
    
    void UpdateSelectionData(IEnumerable<object> previousSelectedItems, IEnumerable<object> currentSelectedItems)  
    {  
        Monkey model = (currentSelectedItems.FirstOrDefault() as Monkey);  
    
        Navigation.PushAsync(new PokeDetailPage(model));  
    
        myCollectionView.SelectedItem = null;  
    }  
    

    Update:

    You can just set the binded model of property SelectedItem to nulll.

    I made a test on my side , and it works properly. You can refer to the following code:

    <CollectionView ItemsSource="{Binding Monkeys}"   
                     x:Name="myCollectionView"  
                    SelectedItem="{Binding SelectedMonkey,Mode=TwoWay}"  
                    SelectionChangedCommand="{Binding SelectedItemCommand}"  
                    SelectionMode="Single">  
    

    </CollectionView>

    The ViewModel is MonkeysViewModel

       public class MonkeysViewModel : INotifyPropertyChanged  
        {  
            readonly IList<Monkey> source;  
            Monkey selectedMonkey;  
      
            public ObservableCollection<Monkey> Monkeys { get; private set; }  
      
            public Monkey SelectedMonkey  
            {  
                get  
                {  
                    return selectedMonkey;  
                }  
                set  
                {  
                    if (selectedMonkey != value)  
                    {  
                        selectedMonkey = value;  
                        OnPropertyChanged();  
                    }  
                }  
            }  
      
      
            public ICommand SelectedItemCommand { get; set; }  
      
            public MonkeysViewModel()  
            {  
                source = new List<Monkey>();  
                CreateMonkeyCollection();  
      
                selectedMonkey = Monkeys.Skip(3).FirstOrDefault();  
      
      
      
                SelectedItemCommand = new Command(async () =>  
                {  
      
                    if (SelectedMonkey!=null) {  
                        var nav = Application.Current.MainPage;  
      
                        await nav.Navigation.PushAsync(new PokeDetailPage(SelectedMonkey));  
      
                        SelectedMonkey = null;  
                    }  
      
                });  
      
      
            }  
      
            void CreateMonkeyCollection()  
            {  
                source.Add(new Monkey  
                {  
                    Name = "Baboon",  
                    Location = "Africa & Asia",  
                    Details = "Baboons are African and Arabian Old World monkeys belonging to the genus Papio, part of the subfamily Cercopithecinae.",  
                    ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/f/fc/Papio_anubis_%28Serengeti%2C_2009%29.jpg/200px-Papio_anubis_%28Serengeti%2C_2009%29.jpg"  
                });  
      
                source.Add(new Monkey  
                {  
                    Name = "Capuchin Monkey",  
                    Location = "Central & South America",  
                    Details = "The capuchin monkeys are New World monkeys of the subfamily Cebinae. Prior to 2011, the subfamily contained only a single genus, Cebus.",  
                    ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/4/40/Capuchin_Costa_Rica.jpg/200px-Capuchin_Costa_Rica.jpg"  
                });  
      
                source.Add(new Monkey  
                {  
                    Name = "Blue Monkey",  
                    Location = "Central and East Africa",  
                    Details = "The blue monkey or diademed monkey is a species of Old World monkey native to Central and East Africa, ranging from the upper Congo River basin east to the East African Rift and south to northern Angola and Zambia",  
                    ImageUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/BlueMonkey.jpg/220px-BlueMonkey.jpg"  
                });  
      
      
                Monkeys = new ObservableCollection<Monkey>(source);  
            }  
      
            #region INotifyPropertyChanged  
            public event PropertyChangedEventHandler PropertyChanged;  
      
            void OnPropertyChanged([CallerMemberName] string propertyName = null)  
            {  
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));  
            }  
            #endregion  
        }  
    

    Best Regards,

    Jessie Zhang

    ---
    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Was this answer helpful?


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.