c# - WPF 中的键值对组合框

标签 c# .net wpf xaml combobox

假设我有绑定(bind)到 ComboBox 的键值对集合(Ex Key=MSFT Value=MSFT Microsoft)。 DisplayMemeberPath=值。以下需要完成

  • 在选择项目时,只需要在 Combo 中显示 Key,

  • 用户还可以在 Combo 中键入一个全新的值。

我想不出同时支持这两种功能的解决方案。解决一个会破坏另一个。

<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"));

并将其绑定(bind)到您拥有的组合框

cmbBrokers.DisplayMemberPath = "_Key";
cmbBrokers.SelectedValuePath = "_Value";

cmbBrokers.ItemsSource = cbp;

当您需要访问它时,只需执行此操作

ComboBoxPairs cbp = (ComboBoxPairs)cmbBrokers.SelectedItem;

string _key = cbp._Key;
string _value = cbp._Value;

这就是您需要做的所有事情。

关于c# - WPF 中的键值对组合框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8521152/

相关文章:

c# - Windows 窗体应用程序基础 : Keeping all forms in one window

c# - Array.ToString() 是否提供有用的输出?

.net - 如何从文件夹中删除特定类型的所有文件

c# - 无需 TFS 或 VSTS 自动部署 Service Fabric 项目

wpf - 数据网格模板列: Items collection must be empty before using ItemsSource.

c# - 只写属性,有什么意义?

c# - 我怎样才能投出一个集合

c# - 具有相同标识的多个程序集。 .NETFramework 门面

c# - WPF 4.5 绑定(bind)到静态属性

wpf - 在 xaml 中以十六进制显示组合框中的字节值列表