"价值''无法转换。"清除ComboBox选择

时间:2015-05-03 08:17:36

标签: wpf combobox key-value selectedvalue non-nullable

我正在尝试清除ComboBox中的选择,但会收到错误

  

"价值''无法转换。"

ComboBox' s ItemSource绑定到键值对列表。 SelectedValue是密钥,DisplayMemberPath绑定到值。

如果ItemSource绑定到普通数据类型(例如字符串)并清除ComboBox中的选定值,则不会发生此错误。但是我需要它作为键值对,因为它的查找。

怀疑错误可能是因为键值对没有相应的空条目或者不能取空值。这可能是框架中的一个错误。如何解决这个问题。看过那些使用Nullable值并进行转换的博客,但由于必须编写显式转换适配器,因此似乎不是解决此问题的好方法。有没有更好的方法来解决这个问题。

尝试将ItemSource绑定设置为可空值。但得到一个不同的错误

  

'&System.Nullable GT;'不包含' Key'的定义没有扩展方法' Key'接受类型为#System; Nullable>'的第一个参数。可以找到(你错过了使用指令或程序集引用吗?)

//XAML

<Combobox 
    Name="CityPostalCodeCombo"
    ItemsSource="{Binding CityList, TargetNullValue=''}"
    SelectedItem="{Binding PostalCode, UpdateSourceTrigger=PropertyChanged, TargetNullValue='', ValidatesOnDataErrors=True, NotifyOnValidationError=True, Mode=TwoWay}"
    SelectedValuePath="Key"
    DisplayMemberPath="Value"
    AllowNull="True"
    MinWidth="150"
    MaxHeight="50">

//Code:  View Model binding
private List<KeyValuePair<string, string>> cityList = GetCityList(); 

// City and postal code list
public List<KeyValuePair<string, string>> CityList
{
  get { return cityList; }
  set
  {
    if (value != cityList)
    {
      cityList = value;
      OnPropertyChanged("CityList");
    }
  }
}             

public KeyValuePair<string, string>? PostalCode
{
    get 
    { 
      return CityList.Where(s =>   s.Key.Equals(postalCode.Value)).First(); 
    }      
    set
    {
      if (value.Key != postalCode.Value)
      {
          postalCode.Value = value.Key;
          OnPropertyChanged("PostalCode");
      }
    }
}

// Populate Cities:
private static List<KeyValuePair<string, string>>GetCityList()
{   
    List<KeyValuePair<string, string>> cities = new List<KeyValuePair<string, string>>();   
    KeyValuePair<string, string> value = new KeyValuePair("94310", "Palo Alto");    
    cities.Add(value);  

    value = new KeyValuePair("94555", "Fremont");   
    cities.Add(value);  

    value = new KeyValuePair("95110", "San Jose");  
    cities.Add(value);  

    return cities;
}

0 个答案:

没有答案
相关问题