Key Value Pair Combobox in WPF

后端 未结 3 717
一生所求
一生所求 2020-12-10 04:49

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

相关标签:
3条回答
  • 2020-12-10 05:30

    I don't think a straight out of the box combobox is the proper UI element for you to use in this situation. The issue here is the combobox is not designed to support key/value pairs, especially if you want the user to be able to add values to the dictionary while you're binding to the key. For example, if you allow them to add a value, how do they add the key or the select the key to update?

    I think the solution is to have two controls: a combobox for the key selection and a textbox for the value input. The values textbox is hidden until the user selects a key. Once the key is selected, have them enter their value input into the textbox and press enter or a button, then set the value to the selected key.

    0 讨论(0)
  • 2020-12-10 05:35

    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.

    0 讨论(0)
  • 2020-12-10 05:36

    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.

    0 讨论(0)
提交回复
热议问题