[英]Key Value Pair Combobox in WPF
考慮我綁定到ComboBox的鍵值對集合(Ex鍵= MSFT值= MSFT Microsoft)。 DisplayMemeberPath =價值。 以下需要完成
在選擇項目時,只需要在組合中顯示鍵,
用戶還可以在組合中鍵入一個全新的值。
我不能提出支持這兩個功能的解決方案。 解決一個打破另一個。
<ComboBox IsTextSearchEnabled="True" Name="cmbBrokers" IsEditable="True"
ItemsSource="{Binding BrokerCodes}" SelectedValuePath="Key"
DisplayMemberPath="Value" Text="{Binding SelectedBroker, Mode=TwoWay}">
我想你想要的是如下。
public class ComboBoxPairs
{
public string _Key { get; set; }
public string _Value { get; set; }
public ComboBoxPairs(string _key,string _value )
{
_Key = _key ;
_Value = _value ;
}
}
然后你繼續這樣使用這個類
List<ComboBoxPairs> cbp = new List<ComboBoxPairs>();
cbp.Add(new ComboBoxPairs("Microsoft", "MSFT"));
cbp.Add(new ComboBoxPairs("Apple", "AAPL"));
並將它綁定到你擁有的組合框
cmbBrokers.DisplayMemberPath = "_Key";
cmbBrokers.SelectedValuePath = "_Value";
cmbBrokers.ItemsSource = cbp;
當你需要訪問它時,就這樣做
ComboBoxPairs cbp = (ComboBoxPairs)cmbBrokers.SelectedItem;
string _key = cbp._Key;
string _value = cbp._Value;
這就是你需要做的。
使用更通用的解決方案擴展Adams示例。
在xaml.cs中創建一個可觀察的集合屬性並為其分配一個集合。
ObservableCollection < KeyValuePair < string , string > > MyCollection { get; set; }
MyCollection = new ObservableCollection < KeyValuePair < string , string > > ( )
{
new KeyValuePair < string , string > ("key1" ,"value1"),
new KeyValuePair < string , string > ("key2" ,"value2")
};
在xaml文件中,將您的observable集合數據綁定到您在后面的代碼中創建的屬性。
<ComboBox Grid.Row="3"
Grid.Column="1"
ItemsSource="{Binding MyCollection}"
DisplayMemberPath="Key" />
如果要顯示值,可以將DisplayMemberPath="Key"
更改為DisplayMemberPath="Value"
。
我不認為開箱即用的組合框是適合您在這種情況下使用的UI元素。 這里的問題是組合框不是為支持鍵/值對而設計的,特別是如果您希望用戶能夠在綁定到鍵時向字典添加值。 例如,如果您允許它們添加值,他們如何添加密鑰或選擇要更新的密鑰?
我認為解決方案是有兩個控件:用於鍵選擇的組合框和用於值輸入的文本框。 值文本框將隱藏,直到用戶選擇一個鍵。 選擇密鑰后,讓他們在文本框中輸入其值輸入並按Enter或按鈕,然后將值設置為所選密鑰。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.