2009-09-25 97 views
3

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

为了说明使用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提供的完成的实验练习也有错误。

有谁知道如何解决它,使设计师高兴?

干杯,
Berryl

回答

4

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

希望这有助于:)。

+1

现货。让人感到奇怪的是,为什么MS中的好人不能解释这一点,就像你刚刚发布*学习材料一样!干杯 – Berryl 2009-09-25 14:42:13