WPF 转换器抛出对象引用未在设计时设置

WPF Converter throwing Object reference not set at design time

我的 xaml 在设计时遇到错误:

Object not set to an instance of an object.

它只在设计时发生,运行在 运行 时间内完美。错误来自我的转换器,我在下面的代码。我认为这可能是由于没有检查值是否为空或者如果它为空我让它返回空,但我改变了两者并且没有任何区别。

并赞赏想法。谢谢

public class CouponDataSplitterConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter,     CultureInfo culture)
    {
        if (value != null)
        {
            List<SelectionArea> selectionAreasList =
                new List<SelectionArea>((ObservableCollection<SelectionArea>) value);
            foreach (var area in selectionAreasList)
            {
                if (area.AreaName.Contains(parameter.ToString()))
                {
                    return area.SelectionRows;
                }
            }

            return selectionAreasList;
        }
        return "";
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

XAML:

ItemsSource="{Binding Coupon.SelectionAreas, 
        ConverterParameter='Test Parameter',
        Converter={StaticResource CouponDataSplitterConverter}

堆栈跟踪:

at App.UI.Converters.CouponDataSplitterConverter.Convert(Object      value, Type targetType, Object parameter, CultureInfo culture)
at System.Windows.Data.BindingExpression.TransferValue(Object newValue, Boolean isASubPropertyChange)
at System.Windows.Data.BindingExpression.Activate(Object item)
at System.Windows.Data.BindingExpression.AttachToContext(AttachAttempt attempt)
at System.Windows.Data.BindingExpression.AttachOverride(DependencyObject target, DependencyProperty dp)
at System.Windows.Data.BindingExpressionBase.OnAttach(DependencyObject d, DependencyProperty dp)
at System.Windows.StyleHelper.GetInstanceValue(UncommonField`1 dataField, DependencyObject container, FrameworkElement feChild, FrameworkContentElement fceChild, Int32 childIndex, DependencyProperty dp, Int32 i, EffectiveValueEntry& entry)
at System.Windows.StyleHelper.GetChildValueHelper(UncommonField`1 dataField, ItemStructList`1& valueLookupList, DependencyProperty dp, DependencyObject container, FrameworkObject child, Int32 childIndex, Boolean styleLookup, EffectiveValueEntry& entry, ValueLookupType& sourceType, FrameworkElementFactory templateRoot)
at System.Windows.StyleHelper.GetChildValue(UncommonField`1 dataField, DependencyObject container, Int32 childIndex, FrameworkObject child, DependencyProperty dp, FrugalStructList`1& childRecordFromChildIndex, EffectiveValueEntry& entry, ValueLookupType& sourceType, FrameworkElementFactory templateRoot)
at System.Windows.StyleHelper.GetValueFromTemplatedParent(DependencyObject  container, Int32 childIndex, FrameworkObject child, DependencyProperty dp,  FrugalStructList`1& childRecordFromChildIndex, FrameworkElementFactory templateRoot, EffectiveValueEntry& entry)
at System.Windows.StyleHelper.ApplyTemplatedParentValue(DependencyObject container, FrameworkObject child, Int32 childIndex, FrugalStructList`1& childRecordFromChildIndex, DependencyProperty dp, FrameworkElementFactory templateRoot)
at System.Windows.StyleHelper.InvalidatePropertiesOnTemplateNode(DependencyObject container, FrameworkObject child, Int32 childIndex, FrugalStructList`1& childRecordFromChildIndex, Boolean isDetach, FrameworkElementFactory templateRoot)
at System.Windows.FrameworkTemplate.InvalidatePropertiesOnTemplate(DependencyObject container, Object currentObject)
at System.Windows.FrameworkTemplate.HandleBeforeProperties(Object createdObject, DependencyObject& rootObject, DependencyObject container, FrameworkElement feContainer, INameScope nameScope)
at System.Windows.FrameworkTemplate.<>c__DisplayClass0.<LoadOptimizedTemplateContent>b__5(Object sender, XamlObjectEventArgs args)
at System.Xaml.XamlObjectWriter.OnBeforeProperties(Object value)
at System.Xaml.XamlObjectWriter.Logic_CreateAndAssignToParentStart(ObjectWriterContext ctx)
at System.Xaml.XamlObjectWriter.WriteStartMember(XamlMember property)
at System.Xaml.XamlWriter.WriteNode(XamlReader reader)
at System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlReader templateReader, XamlObjectWriter currentWriter)
at System.Windows.FrameworkTemplate.LoadTemplateXaml(XamlObjectWriter objectWriter)
at System.Windows.FrameworkTemplate.LoadOptimizedTemplateContent(DependencyObject container, IComponentConnector componentConnector, IStyleConnector styleConnector, List`1 affectedChildren, UncommonField`1 templatedNonFeChildrenField)
at System.Windows.FrameworkTemplate.LoadContent(DependencyObject container, List`1 affectedChildren)
at System.Windows.StyleHelper.ApplyTemplateContent(UncommonField`1 dataField, DependencyObject container, FrameworkElementFactory templateRoot, Int32 lastChildIndex, HybridDictionary childIndexFromChildID, FrameworkTemplate frameworkTemplate)
at System.Windows.FrameworkTemplate.ApplyTemplateContent(UncommonField`1 templateDataField, FrameworkElement container)
at System.Windows.FrameworkElement.ApplyTemplate()
at System.Windows.FrameworkElement.MeasureCore(Size availableSize)
at System.Windows.UIElement.Measure(Size availableSize)
at System.Windows.ContextLayoutManager.UpdateLayout()
at System.Windows.UIElement.UpdateLayout()

很难分辨什么被设置为 null ,如果未在视图模型构造函数中初始化值(我假设在这种情况下为 MarkSenseCoupon),则值最初可能为 null 。查看 Debugging Your Custom Control at Design Time 以了解有关如何在设计时调试控件的步骤,并只需在 convert 方法的开头放置一个断点即可确定将哪个对象设置为 null。

这个 SO 问题似乎也处理类似的问题 WPF Converter casting causes Visual Studio designer exception ...

如果您收到 NullReferenceException,则某些内容为空。

您的代码明确检查 value 参数是否为空。但是,您的 foreach:

中有这行代码
if (area.AreaName.Contains(parameter.ToString()))

如果 AreaName 属性 有空值(Contains 方法调用会抛出),这一行可能会抛出 NullReferenceException ,或者提供给该方法的 parameter 参数为空(ToString 方法调用将抛出)。

可能值得在您的方法中加入一些调试代码,这样您就可以检查正在使用的变量的状态。我知道您不能使用调试器,因为这是一个设计时问题,因此您可能必须登录到一个临时文本文件或类似文件。