更改列表的显示格式<keyvaluepair <string,string =“”>&gt;

时间:2017-07-03 21:22:59

标签: c# xaml xamarin.forms picker

我正在使用Xamarin.Forms Picker,并且正在填充List<KeyValuePair<string, string>>。问题在于它没有显示我想要的方式。

XAML:

<Picker x:Name="VersionPicker" ItemsSource="{Binding}"/>

C#:

Dictionary<string, string> VersionDictionary = new Dictionary<string, string>()
{
    { "asv1901", "American Standard Version" },
    { "bbe", "Bible In Basic English" },
};
List<KeyValuePair<string, string>> VersionList = VersionDictionary.ToList();

VersionPicker.BindingContext = VersionList;

它产生的是这样......

[asv1901, American Standard Version]

我希望Picker能够沿着这些方向发展......

American Standard Version (asv1901)

有办法做到这一点吗? XAML或C#会很好(因为它纯粹是视觉上的变化,我认为XAML或转换器可能最有意义。)

1 个答案:

答案 0 :(得分:0)

向jdweng致敬(因为他/她只是做了评论而不是回答)......

Dictionary<string, string> VersionDictionary = new Dictionary<string, string>()
{
    { "asv1901", "American Standard Version" },
    { "bbe", "Bible In Basic English" },
};
// take the dictionary<string, string>, turn it into an ienumerable<keyvaluepair<string, string>>, use linq to output the contents, format a new string based on those contents, turn it into list<string>
// "Bible In Basic English (bbe)"
var VersionList = VersionDictionary.AsEnumerable().Select(x => string.Format("{0} ({1})", x.Value, x.Key)).ToList();

VersionPicker.BindingContext = VersionList;

将该选择恢复为适当的格式......

private void VersionPicker_SelectedIndexChanged(object sender, EventArgs e)
{
    var selecteditem = VersionPicker.SelectedItem.ToString();
    // single quotes make it type Char while double quotes make it type String
    Char delimiter = '(';
    // create an array from the string separated by the delimiter
    String[] selecteditemparts = selecteditem.Split(delimiter);
    // take off the end space
    var selecteditemvalue = selecteditemparts[0].Substring(0, (selecteditemparts[0].Length - 1));
    // take off the end )
    var selecteditemkey = selecteditemparts[1].Substring(0, (selecteditemparts[1].Length - 1));
}

作为次要选项(以及我最终使用的那个)......

Dictionary<string, string> VersionDictionary = new Dictionary<string, string>()
{
    { "asv1901", "American Standard Version" },
    { "bbe", "Bible In Basic English" },
};

var VersionList = new List<string>();

// keyvaluepair is a single instance and dictionary is a collection of keyvaluepairs
foreach (KeyValuePair<string, string> version in VersionDictionary)
{
    var key = version.Key.ToUpper();
    var value = version.Value;
    // "Bible In Basic English (BBE)"
    VersionList.Add(string.Format("{0} ({1})", value, key));
}

这对我的新手编码大脑更有意义。我确信jdweng的linq例子更简洁。