Search code examples
c#xamlxamarin.formscollectionview

SelectionChanged event of the CollectionView opens when the page is loaded


I have a CollectionView with the SelectionChanged event, which should be read as soon as certain items are selected or deselected. Actually the application enters into that event as soon as the page containing the CollectionView opens. How to solve?

xaml

<CollectionView               
            x:Name="CategoryView" 
            RelativeLayout.WidthConstraint="{ConstraintExpression
            Type=RelativeToParent,
            Property=Width,
            Factor=1}"
            RelativeLayout.YConstraint="{ConstraintExpression
            Type=Constant,
            Constant=60}"             
            Margin="10,0,10,0"
            HeightRequest="700"
            SelectionMode="Multiple"
            SelectionChanged="CategoryView_SelectionChanged">
            <CollectionView.Footer>
                <Button
                    HeightRequest="120"
                    BackgroundColor="Transparent"/>
            </CollectionView.Footer>
            <CollectionView.ItemsLayout>
                <GridItemsLayout Orientation="Vertical" Span="2" VerticalItemSpacing="1" HorizontalItemSpacing="4"/>
            </CollectionView.ItemsLayout>
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Grid BackgroundColor="{Binding myBackGroundColor}">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="36"/>
                            <RowDefinition Height="33"/>
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="30"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>

                        <Image Grid.Row="0" Grid.RowSpan="2" Grid.Column="0" Grid.ColumnSpan="2" Source="{Binding Image}"/>
                        <Label Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2"  Text="{Binding Titolo}" FontSize="19" FontAttributes="Bold" TextColor="White" Margin="13,0,0,0"/>
                        <Image Grid.Row="0" Grid.Column="0" Source="checked.png" IsVisible="{Binding Vis}" Margin="13,5,0,0"/>
                    </Grid>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>

c#

 private async void CategoryView_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var selected = e.CurrentSelection;         
        ClassCategory model = e.CurrentSelection.FirstOrDefault() as ClassCategory;

        WebClient clientw = new WebClient();
        clientw.Credentials = new NetworkCredential("account", "password");
        string Frasi1 = "ftp://[email protected]/htdocs/" + "Obiettivo" + ".json";
        string contents1 = await clientw.DownloadStringTaskAsync(Frasi1);
        ObservableCollection<FraseClass> FrasiJsonOnline1 = JsonConvert.DeserializeObject<ObservableCollection<FraseClass>>(contents1);
        Frasi.ItemsSource = FrasiJsonOnline1;
       
        ViewFrasi.IsVisible = true;
        
        model.myBackGroundColor = Color.Transparent;
        model.Vis = true;

        list.Clear();
        foreach (ClassCategory cat in selected)
        {
            list.Add(cat.Titolo);
        }
    }

Solution

  • I make a code sample with the part for the pre-selection or your reference.

    Xaml:

      <ContentPage.Content>
        <CollectionView
            x:Name="CategoryView"
            Margin="10,0,10,0"
            HeightRequest="700"
            ItemsSource="{Binding classCategories}"
            SelectedItems="{Binding SelectedCategories}"
            SelectionChanged="CategoryView_SelectionChanged"
            SelectionMode="Multiple">
            <CollectionView.Footer>
                <Button BackgroundColor="Transparent" HeightRequest="120" />
            </CollectionView.Footer>
            <CollectionView.ItemsLayout>
                <GridItemsLayout
                    HorizontalItemSpacing="4"
                    Orientation="Vertical"
                    Span="2"
                    VerticalItemSpacing="1" />
            </CollectionView.ItemsLayout>
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Grid>
                        <!--  BackgroundColor="{Binding myBackGroundColor}"  -->
                        <Grid.RowDefinitions>
                            <RowDefinition Height="36" />
                            <RowDefinition Height="33" />
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="30" />
                            <ColumnDefinition Width="*" />
                        </Grid.ColumnDefinitions>
    
                        <Image
                            Grid.Row="0"
                            Grid.RowSpan="2"
                            Grid.Column="0"
                            Grid.ColumnSpan="2"
                            Source="{Binding Image}" />
                        <Label
                            Grid.Row="1"
                            Grid.Column="0"
                            Grid.ColumnSpan="2"
                            Margin="13,0,0,0"
                            FontAttributes="Bold"
                            FontSize="19"
                            Text="{Binding Titolo}"
                            TextColor="White" />
                        <Image
                            Grid.Row="0"
                            Grid.Column="0"
                            Margin="13,5,0,0"
                            IsVisible="{Binding Vis}"
                            Source="pink.jpg" />
                    </Grid>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
    

    Code behind:

     public partial class MainPage : ContentPage, INotifyPropertyChanged
    {
        public ObservableCollection<ClassCategory> classCategories { get; set; }
    
        public ObservableCollection<object> SelectedCategories { get; set; }
    
      
        public MainPage()
        {
            InitializeComponent();
            classCategories = new ObservableCollection<ClassCategory>()
            {
                new ClassCategory{ Image="pink.jpg", myBackGroundColor="Red", Titolo="A", Vis=true},
                new ClassCategory{ Image="pink.jpg", myBackGroundColor="Green", Titolo="B", Vis=false},
                new ClassCategory{ Image="pink.jpg", myBackGroundColor="Red", Titolo="A", Vis=true},
                new ClassCategory{ Image="pink.jpg", myBackGroundColor="Green", Titolo="B", Vis=false},
                new ClassCategory{ Image="pink.jpg", myBackGroundColor="Red", Titolo="A", Vis=true},
                new ClassCategory{ Image="pink.jpg", myBackGroundColor="Green", Titolo="B", Vis=false},
                new ClassCategory{ Image="pink.jpg", myBackGroundColor="Red", Titolo="A", Vis=true},
                new ClassCategory{ Image="pink.jpg", myBackGroundColor="Green", Titolo="B", Vis=false},
                new ClassCategory{ Image="pink.jpg", myBackGroundColor="Red", Titolo="A", Vis=true},
                new ClassCategory{ Image="pink.jpg", myBackGroundColor="Green", Titolo="B", Vis=false},
    
            };
    
            SelectedCategories = new ObservableCollection<object>()
            {
                classCategories[0], classCategories[3]
            };
    
            this.BindingContext = this;
        }
        int i;
        private void CategoryView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            i++;
            if (i <= 2)//this event would be trigglled twice before you load the page
            {
                return;
            }
            else
            {
                //    var selected = e.CurrentSelection;
                //    ClassCategory model = e.CurrentSelection.FirstOrDefault() as ClassCategory;
    
                //    WebClient clientw = new WebClient();
                //    clientw.Credentials = new NetworkCredential("account", "password");
                //    string Frasi1 = "ftp://[email protected]/htdocs/" + "Obiettivo" + ".json";
                //    string contents1 = await clientw.DownloadStringTaskAsync(Frasi1);
                //    ObservableCollection<FraseClass> FrasiJsonOnline1 = JsonConvert.DeserializeObject<ObservableCollection<FraseClass>>(contents1);
                //    Frasi.ItemsSource = FrasiJsonOnline1;
    
                //    ViewFrasi.IsVisible = true;
    
                //    model.myBackGroundColor = Color.Transparent;
                //    model.Vis = true;
    
                //    list.Clear();
                //    foreach (ClassCategory cat in selected)
                //    {
                //        list.Add(cat.Titolo);
                //    }
            }
    
    
        }      
    
    }
    public class ClassCategory
    {
        public string myBackGroundColor { get; set; }
        public string Image { get; set; }
        public string Titolo { get; set; }
        public bool Vis { get; set; }
    }