【问题标题】:How to submit ListView checkbox values using a footer button?如何使用页脚按钮提交 ListView 复选框值?
【发布时间】:2023-02-15 18:47:54
【问题描述】:

我有一个 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 项目以查找已检查的项目。任何帮助表示赞赏

【问题讨论】:

    标签: c# xamarin xamarin.forms checkbox android-listview


    【解决方案1】:

    要从 ListView 中获取选中的项目,您可以遍历 ItemsSource 并找出具有 IsChecked 属性的项目以设置为真的.你的 SubmitClick 方法可能看起来像这样:

    protected void SubmitClick(object sender, EventArgs e)
    {
        // Loop over the SymptomList and get the checked items
        foreach (var symptom in SymptomList)
        {
            if (symptom.IsChecked)
            {
                // Create a new AssessmentModel object for the checked item
                // You can replace the True with the appropriate severity value
                var assessment = new AssessmentModel(UserID, symptom.SymptomName, True, severity);
                
                // Do something e.g. add it to a list
            }
        }
    
        this.Navigation.PopAsync();
    }
    

    【讨论】:

      猜你喜欢
      • 2015-10-14
      • 2017-03-29
      • 1970-01-01
      • 2018-12-13
      • 2013-08-12
      • 2014-05-13
      • 2019-08-22
      • 2019-06-17
      • 2015-12-02
      相关资源
      最近更新 更多