3

WPF の学習の一環として、"Using Data Binding in WPF" ( http://windowsclient.net/downloads/folders/hands-on-labs/entry3729.aspx ) という MS ラボの演習を終えました。

IMul​​tiValueConverter の使用を説明するために、ブール値の結果を使用してデータ バインディングが現在のユーザーに関連するかどうかを判断するコード化された実装があります。変換操作のコードは次のとおりです。

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 が提供する完成したラボ演習にもエラーがあります。

デザイナーを満足させるために修正する方法を知っている人はいますか?

乾杯、
ベリル

4

1 に答える 1

4

ここでの問題は、デザイン モードと実行時で異なる 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);
}

別のアプローチは、バインディングのソースとして Application.Current を使用しないことです。

お役に立てれば :)。

于 2009-09-25T14:21:27.100 に答える