使用 IMultiValueConverter 的 Wpf 数据绑定(bind)和转换错误

标签 wpf data-binding converters imultivalueconverter

作为学习 WPF 的一部分,我刚刚完成了名为“在 WPF 中使用数据绑定(bind)”的 MS 实验室练习 ( http://windowsclient.net/downloads/folders/hands-on-labs/entry3729.aspx )。

为了说明如何使用 IMultiValueConverter,有一个预编码的实现,其中 bool 结果用于确定数据绑定(bind)是否与当前用户相关。以下是转换操作的代码:

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 提供的完成的实验练习也有错误。

有人知道如何修复它以使设计师满意吗?

干杯,
贝里尔

最佳答案

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

希望这有帮助:)。

关于使用 IMultiValueConverter 的 Wpf 数据绑定(bind)和转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1477482/

相关文章:

c# - 按类型查找 WPF 窗口中的所有控件

c# - 是否可以创建一个控制台窗口(由 AllocConsole 创建)作为 GUI 子窗口?如果是这样,如何?

wpf listview 失去焦点

apache-flex - Flex 中的某些 [Bindable] 属性有效,有些则无效

python - 为什么我会收到 discord.py AttributeError : 'str' object has no attribute 'trigger_typing'

c# - 如何在其他类中使用方法?

c# - Winforms 数据绑定(bind) : Can a TypeConverter be used instead of the Format/Parse events?

wpf - 如何使用转换将 WPF 单选按钮选择绑定(bind)到 Viewmodel?

将 IEEE 754 打包比特流转换为浮点单精度

c# - 要构造的字节数组