简体   繁体   中英

WPF Combobox binding to dictionary - wrong value returned

I have a very simple use case: a property with NotifyPropertyChanged() event, a Dictionary<string, string> with some static data and a combobox.

The CB is defined like so:

    <ComboBox ItemsSource="{Binding AllThings}" DisplayMemberPath="Value" 
SelectedValuePath="Key" SelectedItem="{Binding Thing, Mode=TwoWay, 
UpdateSourceTrigger=PropertyChanged}">

The VM contains:

public Dictionary<string, string> AllThings { get; set; }= new Dictionary<string, string>{["a"] = "b"};

    private string thing;

    public string Thing
    {
      get
      {
        return this.thing;
      }
      set
      {
        if (this.thing != value)
        {
          this.thing = value;
          this.OnPropertyChanged();
        }
      }
    }

When the user selects the value, instead of "b" i am getting a strange looking string: [a, b] in the value inside the Thing setter.

I want to display "b" and store "a" in the "Thing".

UPD Likewise, setting the Thing to b does not result in b being selected in the list.

Use SelectedValue instead of SelectedItem. The Item is the key/value pair in the dictionary which is not what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM