【问题标题】:is it possible to assign key/value to a picker?是否可以将键/值分配给选择器?
【发布时间】:2022-09-23 23:42:46
【问题描述】:

我正在尝试使用类似于 html\'s 的选择器

<select>
<option value=\"KEY\">Value</option>
</select>

但是我找不到与此相关的任何内容。我有一些类似的东西

List<KeyValuePair<int, string>> KVP = {1: \"test\", 2: \"test2\"}

当前的xml:

<StackLayout x:Name=\"PickerStack\">
                <Picker x:Name=\"DefaultPicker\"
                        Title=\"---Select a map---\" 
                        ItemsSource=\"{Binding GPXList_PickerList}\" 
                        SelectedIndexChanged=\"PickerStack_Selected\" 
                        SelectedItem=\"{Binding PickerStack_Selection}\" />

后面的当前代码:

    var ResultConvert = JsonConvert.DeserializeObject<GPSAPI_GPXList[]>(ResultJSON);
            List<int> gpxList_ID = ResultConvert.Select(x => x.gpxList_ID).ToList();
            List<string> gpxList_TrailHead_Name = ResultConvert.Select(x => x.gpxList_TrailHead_Name).ToList();
            GPXList_Dictionary = ResultConvert.ToDictionary(x => x.gpxList_ID, x => x.gpxList_TrailHead_Name);
//
            // call for my picker to be populated
            PickerView(GPXList_PickerItems);

        }

        //
        // fill the picker with retrieved API values
        public void PickerView(List<KeyValuePair<int, string>> PickerSource)
        {
            DefaultPicker.ItemsSource = PickerSource;
        }

        //
        // observe the PickerStack and retrieve values on change
        private void PickerStack_Selected(object sender, EventArgs e)
        {
            Picker PickerSelection = sender as Picker;
            TrailText.Text = PickerSelection.SelectedItem.ToString();
        }

并希望只向用户显示值但将密钥返回给程序

public List<KeyValuePair<int, string>> GPXList_PickerItems { get; set; }
  • GPXList_PickerList 的类型是什么?你能分享你的模型课吗?为什么不更新GPXList_PickerList,而是直接覆盖ItemsSource
  • 使用 ItemDisplyayBinding 指定向用户显示的属性。
  • @Jason ItemDisplayBinding 向用户显示,但它没有将键分配给我可以分辨的显示值。
  • @Cfun 我没有注意到我正在这样做。我现在更新代码
  • SelectedItem 将整个 KeyValuePair 作为您需要转换的对象返回

标签: c# android xamarin


【解决方案1】:

正如杰森所说,使用ItemDisplayBinding

   <Picker x:Name="DefaultPicker"
                        Title="---Select a map---" 
                        ItemsSource="{Binding GPXList_PickerList}" 
                        SelectedIndexChanged="PickerStack_Selected" 
                        SelectedItem="{Binding PickerStack_Selection}"
                        ItemDisplayBinding="{Binding Value}" />
void PickerStack_Selected(object sender, EventArgs e)
{
    string key;
    if (sender != null)
        key = ((KeyValuePair<int, string>)sender).Key;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-08
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    • 1970-01-01
    • 2023-04-07
    相关资源
    最近更新 更多