xamarin 如何使用页脚按钮提交ListView复选框值?

nnsrf1az  于 2023-02-27  发布在  其他
关注(0)|答案(1)|浏览(104)

我有一个ListView,它绑定到视图模型中的一些数据。在ListView中,每一行都是一个复选框和一个症状的名称(例如咳嗽)。在ListView的末尾,在页脚中,我有一个按钮来提交用户选中的所有复选框。

<ListView x:Name="SymptomsListView" ItemsSource="{Binding SymptomList}" HasUnevenRows="True" SelectionMode="None" Footer="">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout Orientation="Horizontal" Padding="12,0,0,0">
                    <CheckBox IsChecked="{Binding IsChecked}" Color="ForestGreen" WidthRequest="50" HeightRequest="50" />
                    <Label Text="{Binding SymptomName}" VerticalOptions="Center" Margin="0,20" FontSize="24" TextColor="Black" />
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
    <ListView.FooterTemplate>
        <DataTemplate>
            <ContentView>
                <StackLayout>
                    <Button Text="Submit" TextColor="{StaticResource AppTextColor}" FontAttributes="Bold" FontSize="20" WidthRequest="220" HeightRequest="50" Margin="0,15" HorizontalOptions="Center" CornerRadius="10" BackgroundColor="{StaticResource ButtonColor}" Clicked="SubmitClick"/>
                </StackLayout>
            </ContentView>
        </DataTemplate>
    </ListView.FooterTemplate>
</ListView>

在后面的代码中,我希望按钮按下后提交选中的复选框作为每个选中项的新对象。格式在注解代码中解释-

protected void SubmitClick(object sender, EventArgs e)
{
    // Result output per symptom for the user e.g.
    // If Breathlessness is checked with severity 4, Cough is checked with severity 8 & PTSD is checked with severity 2
    // new AssessmentModel(UserID, Breathlessness, True, 4);
    // new AssessmentModel(UserID, Cough, True, 8);
    // new AssessmentModel(UserID, PTSD, True, 2);

    // CODE HERE

    this.Navigation.PopAsync();
}

我该怎么做呢?从我所看到的来看,没有办法在ListView项目上循环来找到哪些被选中了。任何帮助都很感激

ibrsph3r

ibrsph3r1#

尝试使用命令而不是Clicked事件,以便在ViewModel中处理逻辑。

<Button Text="Submit" Command="{Binding Submit}"/>

在ViewModel中,处理命令:

public ViewModel()
{
    // ...
    Submit = new Command(ExecuteSubmit);
}

private ObservableCollection<Symptom> symptomList;
public ObservableCollection<Symptom> SymptomList
{
    get => symptomList;
    set
    {
        if (symptomList != value)
        {
            symptomList = value;
            OnPropertyChanged("SymptomList");
        }
    }
}
 
public void ExecuteSubmit()
{
    foreach(Symptom item in SymptomList)
    {
        if (item.IsChecked)
        {
            new AssessmentModel(UserID, item.Symptom, True, item.Severity);
        }
    }
    // Rest of your logic here
}

相关问题