I am trying to clear the selection in a ComboBox
but get an error
"Value '' could not be converted."
The ComboBox
's ItemSource
is bound to a key-value pair list. The SelectedValue
is the Key and the DisplayMemberPath
is bound to the Value.
If the ItemSource
is bound to an ordinary datatype, such as a string, and clear the selected value in ComboBox
, this error doesn't occur. But I needed it as a Key-Value pair since its a lookup.
Suspect that the error could be because the key-value pair has no corresponding null entry or could not take a null value. Could this a bug in the framework. How to resolve this. Seen the blogs that says use Nullable value and do the conversion, but doesn't appear to be a good way to resolve this since an explicit conversion adapter have to be written. Is there a better way to resolve this.
Tried setting ItemSource
binding to nullable value. But get a different error
'System.Nullable>' does not contain a definition for 'Key' and no extension method 'Key' accepting a first argument of type 'System.Nullable>' could be found (are you missing a using directive or an assembly reference?)
//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;
}