XAML 如何在.NET MAUI中获取所选复选框的值/名称

kninwzqo  于 2022-12-07  发布在  .NET
关注(0)|答案(1)|浏览(208)

我有一个动态复选框,

private async void GetOffices()
{
    string url = $"{baseurl}/get-offices";

    var response = await httpservices.SendGetRequest(url);

    for (int i = 0; i < response.Count; i++)
    {
        Offices.Add(new Office() { id = (string)response[i]["id"], OfficeName = (string)response[i]["office_name"] });
    }
}

我的XAML如下所示:

<CollectionView ItemsSource="{Binding Offices}">
    <CollectionView.ItemTemplate>
        <DataTemplate x:DataType="viewmodel:Office" >
            <Grid Padding="5">
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto" />
                    <RowDefinition Height="Auto" />
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" />
                    <ColumnDefinition Width="*" />
                </Grid.ColumnDefinitions>

                <Frame Grid.ColumnSpan="2" Padding="15" BackgroundColor="LightBlue" x:Name="OfficeSelection" CornerRadius="0">
                    <Grid Grid.ColumnSpan="2" RowDefinitions="Auto,Auto" ColumnDefinitions="40,*">

                        <CheckBox Grid.Column="0" x:Name="{Binding OfficeName}" CheckedChanged="OnCheckBoxCheckedChanged"/>
                        <Label TextTransform="Uppercase" Padding="10" FontSize="Default" Text="{Binding OfficeName}" Grid.Column="1"></Label>

                    </Grid>
                </Frame>

            </Grid>
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

它将显示如下:

我想做的是,当我点击继续按钮,我可以得到所有选中的复选框名称或值,其中在这种情况下是:入场券、收银台、会议霍尔并将其存储在数组中?
这是我的按钮XAML:

<Button
Grid.Row="1"
Grid.Column="0"
Margin="5"
BorderWidth="0"
Command="{Binding GetSelectedOfficesCommand}"
CornerRadius="0"
Text="Continue" />

[RelayCommand]
public void GetSelectedOffices()
{
  //CODe HERE     
       
}

MAUI相关的MS文档对我来说很混乱。有人能给予我一个代码片段来解决这个问题吗?

hfwmuf9z

hfwmuf9z1#

您应该向office视图模型添加一个布尔属性,并将其绑定到复选框IsChecked。然后在GetSelectedOffices函数中,您只需按此属性进行过滤:

var selectedNames = Offices.Where(x => x.IsSelected).Select(x => x.OfficeName);

相关问题