で選択をクリアしようとしてComboBoxいますが、エラーが発生します
「値 '' を変換できませんでした。」
はキーと値のペアのリストにバインドされていますComboBox。ItemSourceはSelectedValueキーで、DisplayMemberPathは値にバインドされています。
がItemSource文字列などの通常のデータ型にバインドされていて、 で選択した値をクリアするとComboBox、このエラーは発生しません。しかし、ルックアップであるため、キーと値のペアとして必要でした。
エラーの原因として、キーと値のペアに対応する null エントリがないか、null 値を取得できなかったことが考えられます。これはフレームワークのバグでしょうか。これを解決する方法。Nullable 値を使用して変換を行うというブログを見ましたが、明示的な変換アダプターを作成する必要があるため、これを解決する良い方法ではないようです。これを解決するより良い方法はありますか。
ItemSourcenull許容値へのバインディングを設定しようとしました。しかし、別のエラーが発生します
'System.Nullable>' には 'Key' の定義が含まれておらず、タイプ 'System.Nullable>' の最初の引数を受け入れる拡張メソッド 'Key' が見つかりませんでした (using ディレクティブまたはアセンブリ参照がありませんか?)
//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;
}