WPF中的键值对组合框

Rau*_*uld 10 .net c# 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}">
Run Code Online (Sandbox Code Playgroud)

小智 32

我想你想要的是如下.

public class ComboBoxPairs
{
    public string _Key { get; set; }
    public string _Value { get; set; }

    public ComboBoxPairs(string _key,string _value )
    {
        _Key = _key ;
        _Value = _value ;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你继续这样使用这个类

List<ComboBoxPairs> cbp = new List<ComboBoxPairs>();

cbp.Add(new ComboBoxPairs("Microsoft", "MSFT"));
cbp.Add(new ComboBoxPairs("Apple", "AAPL"));
Run Code Online (Sandbox Code Playgroud)

并将它绑定到你拥有的组合框

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

cmbBrokers.ItemsSource = cbp;
Run Code Online (Sandbox Code Playgroud)

当你需要访问它时,就这样做

ComboBoxPairs cbp = (ComboBoxPairs)cmbBrokers.SelectedItem;

string _key = cbp._Key;
string _value = cbp._Value;
Run Code Online (Sandbox Code Playgroud)

这就是你需要做的.


SIN*_*ITY 6

用更通用的解决方案扩展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")
};
Run Code Online (Sandbox Code Playgroud)

在xaml文件中,将您可观察的集合绑定到您在后面的代码中创建的属性。

<ComboBox Grid.Row="3"
          Grid.Column="1"
          ItemsSource="{Binding MyCollection}"
          DisplayMemberPath="Key" />
Run Code Online (Sandbox Code Playgroud)

您可以更改DisplayMemberPath="Key"DisplayMemberPath="Value",如果你要显示的值来代替。