XAML foreach()错误对象引用未设置为对象的实例

时间:2010-01-20 00:38:24

标签: c# .net xaml object

我在Visual Studio中出现了一个奇怪的XAML错误。我已将它隔离到下面的代码,导致它。使用下面的转换器时,XAML设计器会出错,但应用程序运行正常且没有错误。我喜欢保持代码整洁并删除所有警告和错误,我需要做些什么来摆脱这个?

 [ValueConversion(typeof(double?), typeof(double?))]
public class SummaryConverter : IValueConverter
{
    #region IValueConverter Members
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        CollectionViewGroup group = value as CollectionViewGroup ;
        if (parameter.ToString() == "FieldName")
        {
            double suUnits = 0;
            foreach (var t in group.Items) //This Line here causes error on XAML

            {
                suUnits +=  t.FieldName.GetValueOrDefault();
            }
            return suUnits;
        }
return "";
}

1 个答案:

答案 0 :(得分:2)

您应该为组添加空检查,因为如果尚未绑定“转换”的对象,则组可能为null。这在设计师中经常发生。

我只想将其更改为:

public class SummaryConverter : IValueConverter 
{ 
    #region IValueConverter Members 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
        CollectionViewGroup group = value as CollectionViewGroup ; 
        if ((group != null) && (parameter.ToString() == "FieldName")) // Add null check here!
        { 
            double suUnits = 0; 
            foreach (var t in group.Items) //This Line here causes error on XAML 
             { 
                suUnits +=  t.FieldName.GetValueOrDefault(); 
            } 
            return suUnits; 
        } 
    return ""; 
}