views:

214

answers:

1

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")
        {
            double suUnits = 0;
            foreach (var t in group.Items) //This Line here causes error on XAML

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

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 ""; 
} 
Reed Copsey
It's the "downside" of use the `as` operator. No exceptions are thrown for a failed cast.
Alastair Pitts
Thank you so much! this worked!!!
Traci