简体   繁体   English

WPF组合框绑定到字典-返回错误的值

[英]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. 我有一个非常简单的用例:一个带有NotifyPropertyChanged()事件的属性,一个带有一些静态数据的Dictionary<string, string>和一个组合框。

The CB is defined like so: CB的定义如下:

    <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. 当用户选择的值,而不是“B”我得到一个奇怪的看的字符串: [a, b]value里面Thing二传手。

I want to display "b" and store "a" in the "Thing". 我想显示“ b”并将“ a”存储在“事物”中。

UPD Likewise, setting the Thing to b does not result in b being selected in the list. UPD同样,将Thing设置为b也不会导致在列表中选择b

Use SelectedValue instead of SelectedItem. 使用SelectedValue而不是SelectedItem。 The Item is the key/value pair in the dictionary which is not what you want. 项是字典中不是您想要的键/值对。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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