我在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 "";
}
答案 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 "";
}