作为学习 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/