如何使用 xamarin 表单获取列表视图中切换开关项的 ID
How to get the id of the toggled switch item in the listview using xamarin forms
我有一个列表视图,所有列表视图项目都在右端包含一个开关,如下图所示。
Listview Image
当我 select 一个项目时,开关会触发 Toggled 事件。我的代码在下面添加:
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");
}
型号class:
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; }
}
}
当我单击接受按钮时,我需要所有 selected 项目 [item1,item2] 的 retail_modified_item_id?
获取开关的 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);
}
}
我有一个列表视图,所有列表视图项目都在右端包含一个开关,如下图所示。
Listview Image
当我 select 一个项目时,开关会触发 Toggled 事件。我的代码在下面添加:
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");
}
型号class:
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; }
}
}
当我单击接受按钮时,我需要所有 selected 项目 [item1,item2] 的 retail_modified_item_id?
获取开关的 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);
}
}