在Windows-10中的Windows通用应用程序中使用打印功能时,PrintingRoot.Children.Add(firstPage)获取空例外错误

时间:2016-06-04 07:28:33

标签: c# xaml windows-10-universal

我正在实现几乎完成的打印功能,但是当点击打印按钮时,它会在PrintingRoot.Children.Add(firstPage)中抛出一个空例外。

代码:

protected override void PreparePrintContent()
{
    try
    {
        trys = trysgetorderdetail;
        OrderDetailResponse obj1 = JsonConvert.DeserializeObject<OrderDetailResponse>(trys);
        if (firstPage == null)
        {
            firstPage = new popup(obj1);
        }

        PrintingRoot.Children.Add(firstPage);
        PrintingRoot.InvalidateMeasure();
        PrintingRoot.UpdateLayout();
    }
    catch (HttpRequestException ex)
    {

    }
    catch (Exception ex) { }
}

protected virtual Canvas PrintingRoot
{
    get
    {
        return FindName("printingRoot") as Canvas;
    }   
}

所以建议我一个解决方案

1 个答案:

答案 0 :(得分:0)

根据您的代码路径,可能有很多原因导致空引用异常。并且应该通过调试找到此异常的解决方案。

我会做的是:

  • 检查PrintingRoot是否为空

  • 检查PrintingRoot.Children是否为空

  • 如果存在我们在此处看不到的路径,请继续这样做。

您可以查看如下:

if(PrintingRoot == null) throw new Exception("PrintingRoot object is not set");
if(PrintingRoot.Children == null) throw new Exception("PrintingRoot.Children object is not set");   

之后,您应该将实例设置为您相应找到的句柄。

<强>更新: 现在你知道什么是null。显然FindName("printingRoot") as Canvas没有返回任何有效对象。

因此,原因可能是您的Canvas对象名称为空,或者是其他名称。确保您输入正确。以下是一个例子。

<Canvas Name="PrintingRoot" HorizontalAlignment="Left" Height="100" Margin="215,127,0,0" VerticalAlignment="Top" Width="100"/>

注意Name属性!