WPF中的键值对组合框

时间:2011-12-15 13:53:19

标签: c# .net wpf xaml combobox

考虑我绑定到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}">

3 个答案:

答案 0 :(得分:30)

我想你想要的是如下。

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;

这就是你需要做的一切。

答案 1 :(得分:3)

使用更通用的解决方案扩展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"

答案 2 :(得分:-4)

我不认为开箱即用的组合框是适合您在这种情况下使用的UI元素。这里的问题是组合框不是为支持键/值对而设计的,特别是如果您希望用户能够在绑定到键时向字典添加值。例如,如果您允许它们添加值,他们如何添加密钥或选择要更新的密钥?

我认为解决方案是有两个控件:用于键选择的组合框和用于值输入的文本框。值文本框将隐藏,直到用户选择一个键。选择密钥后,让他们在文本框中输入值输入,然后按enter或按钮,然后将值设置为所选密钥。

相关问题