开发者

XAML foreach() Error Object reference not set to an instance of an object

开发者 https://www.devze.com 2022-12-17 02:22 出处:网络
I have a strange XAML Error that comes up in Visual Studio.I have Isolated it to the code below which causes it.The XAML designer errors when the converter below is used, however the application runs

I have a strange XAML Error that comes up in Visual Studio. I have Isolated it to the code below which causes it. The XAML designer errors when the converter below is used, however the application runs just fine without error. I like to keep the code tidy and remove all warnings and errors, what do I need to do to get rid of this one?

 [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")
        开发者_如何学C{
            double suUnits = 0;
            foreach (var t in group.Items) //This Line here causes error on XAML

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


You should add a null check for group, since group may be null if the object being "converted" hasn't been bound yet. This happens frequently in the designer.

I would just change this to:

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 ""; 
} 
0

精彩评论

暂无评论...
验证码 换一张
取 消