如何使用xamarin表单获取列表视图中已切换开关项的ID

时间:2019-03-27 10:31:50

标签: listview xamarin.forms uiswitch

我有一个列表视图,所有列表视图项的右端都包含一个开关,如下图所示。

Listview Image

当我选择一个项目时,开关将触发“切换”事件。我的代码添加如下:

Xaml:

 <Switch IsToggled="false"  Margin="210,2,2,2" Toggled="Switch_Toggled" />

Xaml.cs:

 private void Switch_Toggled(object sender, ToggledEventArgs e)
    {
       // I need the retail_modified_item_id of the selected item, how I can access that

    }
private void accept(object sender, EventArgs args)
    {
       // fetch all selected items and display success 
        DisplayAlert("Success", "Request Accepted and Updated", "OK");
    }

模型类:

namespace XamNative.Models
{

public class Human
{
    public string name { get; set; }
    public int retail_modified_item_id { get; set; }
    public double old_price { get; set; }
    public double new_price { get; set; }
}
}

当我单击“接受”按钮时,我需要所有选定项目的“ retail_modified_item_id” [

1 个答案:

答案 0 :(得分:0)

获取开关的BindingContext,并从中获取所需的ID

// list to hold all selected values
List<string> selected = new List<string>();

private void Switch_Toggled(object sender, ToggledEventArgs e)
{
   // I need the retail_modified_item_id of the selected item, how I can access that

   var switch = (Switch)sender;
   var human = (Human)switch.BindingContext;
   var id = human.retail_modified_item_id;

   // add/remove id from selected based on IsToggled
   if (switch.IsToggled) {
     if (!selected.Contains(id)) selected.Add(id);
   } else {
     if (selected.Contains(id)) selected.Remove(id);
   }
}