Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Key Value Pair Combobox in WPF

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

  • 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}">
like image 747
Rauld Avatar asked Dec 15 '11 13:12

Rauld


2 Answers

Expanding on Adams example with a even more generic solution.

In the xaml.cs create a observable collection property and assign a collection to it.

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

In the xaml file databind your observable collection to the property you created in the code behind.

<ComboBox Grid.Row="3"
          Grid.Column="1"
          ItemsSource="{Binding MyCollection}"
          DisplayMemberPath="Key" />

You can change the DisplayMemberPath="Key" to DisplayMemberPath="Value" if you wish to display the value instead.

like image 196
SINGULARITY Avatar answered Oct 26 '22 15:10

SINGULARITY


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 ;
    }
}

Then you go on and use this class like this

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.

like image 38
Alam Avatar answered Oct 26 '22 14:10

Alam