mercredi 30 juin 2021

Count selected checkboxes in collectionview xamarin

I have a collection view with a checkbox. I want to count the amount of checkboxes which have been selected and show that value in a label (string Sel). I think I have mostly done it however the label doesn't update. I think this is due to not calling OnProperty changed in the correct place which would update the label. I'm still rapping my head round MVVM. Thanks

ModelView:

public class MeetAWalkerViewModel : INotifyPropertyChanged
 {
       
       
     public ObservableCollection<PetProfile> source;
     public ObservableCollection<PetProfile> PetInfo { get; private set; }
     public ObservableCollection<PetProfile> EmptyPetInfo
     {
         get => source;
         private set
         {
             if (value != source)
             {
                 source = value;
                 OnPropertyChanged(nameof(EmptyPetInfo));
             }
         }
     }
     
        
     public string Sel { get; private set; }

     public MeetAWalkerViewModel()
     {
            
         var count = EmptyPetInfo.Count(t => t.Selected);
         Sel = "Amount of selected pets" + Convert.ToString(count);
     }

       
        
     #region INotifyPropertyChanged
     public event PropertyChangedEventHandler PropertyChanged;
     void OnPropertyChanged([CallerMemberName] string propertyName = null)
     {
         PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
     }
     #endregion
 }

Xaml:

<CollectionView  x:Name="petCollectionView"  ItemsSource="{Binding EmptyPetInfo}">
                 <CollectionView.ItemTemplate>
                     <DataTemplate>
                         <Grid Padding="10" RowDefinitions="80" ColumnDefinitions="120,60,60">
                             <Image Grid.Column="0"
                                Grid.Row="0"
                                x:Name="PetImage"
                                Source="{Binding imageUrl}"/>
                             <Label Grid.Column="1"
                                Grid.Row="0"
                                Text="{Binding PetName}"
                                FontAttributes="Bold"
                                x:Name="labelpetname" VerticalTextAlignment="Center" HorizontalTextAlignment="Center"/>
                             <CheckBox  Grid.Row="0" Grid.Column="2" HorizontalOptions="End" IsChecked="{Binding Selected, Mode=TwoWay}" CheckedChanged="CheckBox_CheckedChanged" BindingContext="{Binding .}"/>
                         </Grid>
                     </DataTemplate>
                 </CollectionView.ItemTemplate>
             </CollectionView>



Aucun commentaire:

Enregistrer un commentaire