我在Lucas Zhang的帮助下创建了一个自定义选择器,您可以在该链接中检查 xamarin custom multiple picker
现在我对这个问题还有另一个疑问。当用户选择一个或多个组时,我需要访问这些选定的参数。
public class Grup
{
public int ID { get; set; }
public string GroupName { get; set; }
public Nullable<int> SubsID { get; set; }
}
这是我使用的模型。选择器通过ViewModel读取组名,如下所示。
public class NewUserViewModel
{
public List<Grup> GroupList { get; set; }
public List<Grup> SelectedGroup { get; set; }
}
我想将这些来自每个选择器的参数保存到此处,然后我将通过API将它们发送到数据库。问题是当用户选择它们并单击保存按钮时,如何访问这些ID。
答案 0 :(得分:0)
一种简单的方法是侦听选择器的选择事件,然后通过遍历pickerStack
像这样(基于卢卡斯·张的样本):
在 PickerView 中:
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class PickerView : ContentView
{
public Group SelectGroup; // add the SelectGroup property which save the result after you select
public ObservableCollection<Group> pickerSource { get; set; }
public PickerView(ObservableCollection<Group> source) //here i change the source to your Group model
{
InitializeComponent();
picker.ItemsSource = source;
}
private void TapGestureRecognizer_Tapped(object sender, EventArgs e)
{
var stack = this.Parent as StackLayout;
stack.Children.Remove(this);
}
private void picker_SelectedIndexChanged(object sender, EventArgs e)
{
var picker = sender as Picker;
SelectGroup = (Group)picker.SelectedItem;
}
}
PickerView.xaml 中的只需添加SelectedIndexChanged
事件:
<Picker Grid.Column="0" x:Name="picker" Title="{Binding GroupName}" ItemDisplayBinding="{Binding ID}" TitleColor="Red" SelectedIndexChanged="picker_SelectedIndexChanged" />
在您的页面中:
public partial class MutiPicker : ContentPage
{
public MutiPicker()
{
InitializeComponent();
}
private void Button_Clicked(object sender, EventArgs e)
{
var source = new ObservableCollection<Group>() { new Group() { ID=111,GroupName="AAA",SubsID=1}, new Group() { ID = 222, GroupName = "BBB", SubsID = 2 }, new Group() { ID = 333, GroupName = "CCC", SubsID = 3 } };
pickerStack.Children.Add(new PickerView(source));
}
//iterate over your pickerviews
private void Update_Clicker(object sender, EventArgs e)
{
foreach (var pickerview in pickerStack.Children)
{
if (pickerview is PickerView && ((PickerView)pickerview).SelectGroup != null)
{
var selectgroup = ((PickerView)pickerview).SelectGroup;//here you will get your select group,then you could get its ID ,GroupName or SubsID
}
}
}
}