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