Key Value Pair Combobox in WPF

后端 未结 3 721
一生所求
一生所求 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: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 cbp = new List();
    
    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.

提交回复
热议问题