mardi 6 juillet 2021

CheckBox create a string from the values of the selected objects

I have a collection view with a checkbox. It looks like the following: [Image][PetName][Checkbox]

I want to create a string with all the names of the pets which have been selected the pass this value through a function.

I have tried the following code but I am getting object reference is null in selectedPets.Add(ob) I'm sure Im proably going the wrong way with this but I am new to coding.

 public List<PetProfile> selectedPets;

private void CheckBox_CheckedChanged(object sender, CheckedChangedEventArgs e)
    {
        var checkbox = sender as CheckBox;
        
        var ob = checkbox.BindingContext as PetProfile;
      
        if (ob != null)
        {
            selectedPets.Add(ob);
        }
     
    }



private string CreatePetName()
    {
        var stringBuilder = new StringBuilder();
        var listlenght = selectedPets.Count;
        
        foreach (var pet in selectedPets)
        {
            if (selectedPets.Count == 0)
            {
                stringBuilder.Append(pet.PetName);
            }
            else if (listlenght > 0 && pet == selectedPets[0] )
            {
                stringBuilder.Append(pet.PetName + " ");
            }
            else if (pet == selectedPets[listlenght])
            {
                stringBuilder.Append(" " + pet.PetName );
            }
            else
            {
                stringBuilder.Append(" " + pet.PetName + " ");
            }               
        }
        return stringBuilder.ToString();
    }


private async void SubmitBtn_Clicked(object sender, EventArgs e)
    {
        var Petnames = CreatePetName();                               
    }

XAML:

<CollectionView  x:Name="petCollectionView"  ItemsSource="{Binding EmptyPetInfo}" HeightRequest="200">
                <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}" BindingContext="{Binding .}" CheckedChanged="CheckBox_CheckedChanged"/>
                        </Grid>
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>



Aucun commentaire:

Enregistrer un commentaire