CheckBox 根据所选对象的值创建一个字符串

CheckBox create a string from the values of the selected objects

我有一个带有复选框的集合视图。 它看起来像下面这样: [图片][PetName][复选框]

我想创建一个字符串,其中包含已选择的所有宠物的名称,并通过函数传递此值。

我已经尝试了以下代码,但我得到的对象引用在 selectedPets.Add(ob) 中为空,我确定我可能用错了方法,但我是编码新手。

 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>

使用前需要先初始化selectedPets

public List<PetProfile> selectedPets = new List<PetProfile>();

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

我建议你不需要使用CheckBox_CheckedChanged事件来获取选中的PetName,你可以创建一个class名字的Petclass,实现INotifyPropertyChanged,通知Selected属性 改变了。

 public class Petclass:ViewModelBase
{
    public string imageUrl { get; set; }
    public string PetName { get; set; }
    private bool _Selected;
    public bool Selected
    {
        get { return _Selected; }
        set
        {
            _Selected = value;
            RaisePropertyChanged("Selected");
        }
    }

}

public class ViewModelBase : INotifyPropertyChanged
{
   
    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

然后加载一些数据以在 collectionview 中进行测试。 foreach EmptyPetInfo Collectionview ItemsSource="{Binding EmptyPetInfo}" 检查 Selected 属性 是真还是假。

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

public partial class Page17 : ContentPage
{
    public ObservableCollection<Petclass> EmptyPetInfo { get; set; }
    public Page17()
    {
        InitializeComponent();

        EmptyPetInfo = new ObservableCollection<Petclass>()
        {
            new Petclass(){imageUrl="check.png",PetName="pet 1"},
            new Petclass(){imageUrl="delete.png",PetName="pet 2"},
            new Petclass(){imageUrl="favorite.png",PetName="pet 3"},
            new Petclass(){imageUrl="flag.png",PetName="pet 4"}

        };
        this.BindingContext = this;
    }

    private void btn1_Clicked(object sender, EventArgs e)
    {
        var stringBuilder = new StringBuilder();
        foreach (Petclass pet in EmptyPetInfo)
        {
            if(pet.Selected)
            {
                stringBuilder.Append(pet.PetName + " ");
            }
        }
        string str = stringBuilder.ToString();
    }
}

使用 ObservableCollection Class,表示一个动态数据集合,在添加、删除项目或刷新整个列表时提供通知。