IMultiValueConverter を使用した Wpf データ バインディングとキャスト エラー
-
16-09-2019 - |
質問
WPF 学習の一環として、「WPF でのデータ バインディングの使用」という MS Lab の演習を終えたところです (http://windowsclient.net/downloads/folders/hands-on-labs/entry3729.aspx).
IMultiValueConverter の使用を説明するために、データ バインディングが現在のユーザーに関連するかどうかを判断するためにブール値の結果が使用される、事前にコード化された実装があります。変換操作のコードは次のとおりです。
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) {
// var rating = int.Parse(values[0].ToString());
var rating = (int)(values[0]);
var date = (DateTime)(values[1]);
// if the user has a good rating (10+) and has been a member for more than a year, special features are available
return _hasGoodRating(rating) && _isLongTimeMember(date);
}
これを XAML で使用するための配線は次のとおりです。
<ComboBox.IsEnabled>
<MultiBinding Converter="{StaticResource specialFeaturesConverter}">
<Binding Path="CurrentUser.Rating" Source="{x:Static Application.Current}"/>
<Binding Path="CurrentUser.MemberSince" Source="{x:Static Application.Current}"/>
</MultiBinding>
</ComboBox.IsEnabled>
コードは正常に実行されますが、XAMLデザイナーは「特定のキャストが無効」でロードされません。エラー。キャストを使用しない方法をいくつか試しましたが、そのうちの 1 つは上記のコードでコメントを付けずに残しました。面白いのは、MS が提供する完了したラボ演習にもエラーがあることです。
デザイナーを満足させるためにそれを修正する方法を知っている人はいますか?
乾杯、
ベリル
解決
ここでの問題は、Application.Current を使用することですが、これはデザイン モードとランタイムでは異なります。
デザイナーを開いたとき、Application.Current は「App」クラス (または任意の名前) にはなりません。したがって、そこには CurrentUser プロパティがなく、エラーが発生します。
それを修正する方法は複数あります。最も簡単な方法は、デザイン モードかどうかを確認することです。
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
if (Application.Current == null ||
Application.Current.GetType() != typeof(App))
{
// We are in design mode, provide some dummy data
return false;
}
var rating = (int)(values[0]);
var date = (DateTime)(values[1]);
// if the user has a good rating (10+) and has been a member for more than a year, special features are available
return _hasGoodRating(rating) && _isLongTimeMember(date);
}
もう 1 つのアプローチは、バインディングのソースとして Application.Current を使用しないことです。
お役に立てれば :)。