WPF 中的键值对组合框 [英] Key Value Pair Combobox in WPF
问题描述
考虑我有绑定到 ComboBox 的键值对集合(Ex Key=MSFT Value=MSFT Microsoft).DisplayMemeberPath=值.需要完成以下工作
Consider I have Key Value Pair Collection (Ex Key=MSFT Value=MSFT Microsoft) which I bind to the ComboBox. DisplayMemeberPath=Value. the Following needs to be accomplished
在选择一个项目时,只需要在 Combo 中显示 Key,
On Selection of a Item only the Key needs to be displayed in Combo,
用户还可以在组合中输入一个全新的值.
the user could also type a brand new value in the Combo.
我无法想出同时支持这两种功能的解决方案.解决一个破坏另一个.
I cant come up with the solution that supports both these features. Solving one breaks the other.
<ComboBox IsTextSearchEnabled="True" Name="cmbBrokers" IsEditable="True"
ItemsSource="{Binding BrokerCodes}" SelectedValuePath="Key"
DisplayMemberPath="Value" Text="{Binding SelectedBroker, Mode=TwoWay}">
推荐答案
我猜你要找的内容如下.
I guess what you're looking for is as follows.
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"));
并将其绑定到您拥有的组合框
And bind it to the combobox you have
cmbBrokers.DisplayMemberPath = "_Key";
cmbBrokers.SelectedValuePath = "_Value";
cmbBrokers.ItemsSource = cbp;
当您需要访问它时,只需执行此操作
And When you need to access it just do this
ComboBoxPairs cbp = (ComboBoxPairs)cmbBrokers.SelectedItem;
string _key = cbp._Key;
string _value = cbp._Value;
这就是您需要做的全部.
This is all you need to do.
这篇关于WPF 中的键值对组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!