使用 IMultiValueConverter 的 Wpf 数据绑定和转换错误
-
16-09-2019 - |
题
作为学习 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 提供的完成的实验练习也有错误。
有谁知道如何修复它才能让设计师满意?
干杯,
贝里尔
解决方案
这里问题是,使用Application.Current,这是在设计模式和运行时不同。
在打开的设计,Application.Current不会是你的“应用程序”类(或任何你的名字)。因此,有没有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作为你的绑定源是
希望这有助于:)
。不隶属于 StackOverflow