2017-07-03 123 views
0

我正在使用Xamarin.Forms Picker,它正在填充List<KeyValuePair<string, string>>。問題在於它沒有以我想要的方式顯示。更改列表的顯示格式<KeyValuePair <字符串,字符串>>

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或轉換器可能最有意義)。

+0

ItemDisplayBinding用於綁定源代碼中顯示的文本。您可以創建您自己的類(或擴展KVP),而不是使用KeyValuePair,其中包含按照您希望的方式格式化的Display屬性。 – Jason

+1

請嘗試以下方法:var VersionList = VersionDictionary.AsEnumerable()。Select(x => string.Format(「{0}({1})」,x.Value,x.Key).ToList(); – jdweng

+0

@jdweng FYI ...在'x.Key)'和'.ToList()'之間需要額外的''''。 – doubleJ

回答

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例子更加簡潔。

相關問題