"Value" cannot be converted. error while clearing selection ComboBox
I am trying to clear a selection in ComboBox
but I get an error
"Value" cannot be converted.
ComboBox
ItemSource
bound to a list of key-value pairs. SelectedValue
is a key and is DisplayMemberPath
bound to a value.
If you ItemSource
bind to regular data types such as string and clear the selected value in ComboBox
, this error does not occur. But I have needed it as a Key-Value pair since looking for it.
Suspect that the error could be caused by the fact that the key-value pair does not have a corresponding null entry or cannot be null. Could it be a bug in the framework. How to solve it. You see blogs that say they use Nullable and do the conversion, but don't seem to be a good way to solve this problem as an explicit conversion adapter has to be written. Is there any better way to solve this problem.
Tried binding ItemSource
to null. But get a different error.
"System.Nullable>" does not contain a definition for "Key" and there is no extension method "Key" that takes a first argument of type "System.Nullable>" (are you missing a using directive or 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;
}
source to share
No one has answered this question yet
Check out similar questions: