【问题标题】:Wpf Data Binding using IMultiValueConverter and casting errors使用 IMultiValueConverter 和转换错误的 Wpf 数据绑定
【发布时间】:2010-12-01 10:32:46
【问题描述】:

作为学习 WPF 的一部分,我刚刚完成了名为“在 WPF 中使用数据绑定”的 MS 实验室练习 (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 设计器不会加载“指定的强制转换无效”。错误。我尝试了几种不使用演员表的方法,其中一种我在上面的代码中没有注释。有趣的是MS提供的一个完成的实验练习也有错误。

有谁知道如何解决它以使设计师满意?

干杯,
浆果

【问题讨论】:

    标签: wpf data-binding converter imultivalueconverter


    【解决方案1】:

    这里的问题是你使用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 作为绑定源。

    希望这会有所帮助:)。

    【讨论】:

    • 正确。让人想知道为什么 MS 的好人不能像您在发布 学习 材料时那样费心地解释这一点!干杯
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-17
    • 1970-01-01
    • 1970-01-01
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多