Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# XAML foreach()错误对象引用未设置为对象的实例_C#_.net_Xaml_Object - Fatal编程技术网

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

C# XAML foreach()错误对象引用未设置为对象的实例,c#,.net,xaml,object,C#,.net,Xaml,Object,我在VisualStudio中遇到了一个奇怪的XAML错误。我已经将它隔离到下面的代码中,这是导致它的原因。使用下面的转换器时,XAML设计器会出错,但是应用程序运行正常,没有错误。我喜欢保持代码整洁,删除所有警告和错误,我需要做些什么来消除这一点 [ValueConversion(typeof(double?), typeof(double?))] public class SummaryConverter : IValueConverter { #region IValueConv

我在VisualStudio中遇到了一个奇怪的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 "";
}

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

我只想将此更改为:

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 ""; 
} 
这是将
用作
操作符的“缺点”。对于失败的强制转换,不会引发异常。