Wpf数据绑定使用IMultiValueConverter和强制类型转换错误

3
作为学习WPF的一部分,我刚刚完成了一个名为“在WPF中使用数据绑定”的微软实验室练习(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设计师无法加载,显示“指定的转换无效”错误。我尝试了几种不使用转换的方法,其中一种在上面的代码中未被注释。有趣的是,微软提供的一个完成的实验练习也出现了这个错误。
有人知道如何修复它以使设计师满意吗?
祝好, Berryl
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作为绑定的源。

希望这可以帮到您 :).


1
一针见血。让人想知道微软的好心人为什么在他们发布“学习”资料时不能像你刚才那样解释清楚!干杯 - Berryl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接