开发者

Initialize Component throws a null reference exception

I have a menu item in a large program that opens a new window. Nothing gets passed into it, it loads a calendar, 3 empty text boxes, 3 labels, 2 buttons and an empty Crystal Report Viewer.

When its running the user clicks on the calendar and this automatically inserts the first and last dates of the selected month into 2 of the text boxes. One button loads a CR report with data from a DB, the other button prints the report.

This works fine on my system but the Initialize Component throws a null reference exception when deployed on a colleagues system. I cannot recreate the exception on my system.

Has anyone any ideas on where I should even start?

Updated

ERROR

System.NullReferenceException: Object reference not set to an instance of an object.
   at System.Windows.Baml2006.Baml2006Reader.Process_PropertyWithConverter()
   at System.Windows.Baml2006.Baml2006Reader.Process_OneBamlRecord()
   at System.Windows.Baml2006.Baml2006Reader.Process_BamlRecords()
   at System.Windows.Baml2006.Baml2006Reader.Read()
   at System.Windows.Markup.WpfXamlLoader.TransformNodes(XamlReader xamlReader, XamlObjectWriter xamlWriter, Boolean onlyLoadOneNode, Boolean skipJournaledProperties, Boolean shouldPassLineNumberInfo, IXamlLineInfo xamlLineInfo, IXamlLineInfoConsumer xamlLineInfoConsumer, XamlContextStack`1 stack, IStyleConnector styleConnector)
   at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings,开发者_JAVA技巧 Uri baseUri)
   at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
   at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
   at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
   at KeyInScreen.RebatesReports.InitializeComponent()
   at KeyInScreen.RebatesReports..ctor()
   at KeyInScreen.Menu.FertiliserRebate_Click(Object sender, RoutedEventArgs e)

XAML Code

<Window x:Class="KeyInScreen.RebatesReports"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Fertiliser Rebates" WindowState="Maximized" 
    xmlns:my="clr-namespace:SAPBusinessObjects.WPF.Viewer;assembly=SAPBusinessObjects.WPF.Viewer" 
    mc:Ignorable="d" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" Height="700" 
    Width="1350">
<Window.Resources>
    <Style TargetType="{x:Type Label}">
        <Setter Property="FontSize" Value="14" />
    </Style>
    <Style TargetType="{x:Type Button}">
        <Setter Property="FontSize" Value="14"/>
    </Style>
    <Style TargetType="{x:Type Calendar}">
        <Setter Property="FontSize" Value="14"/>
    </Style>
    <Style TargetType="{x:Type TextBox}">
        <Setter Property="FontSize" Value="14"/>
    </Style>
</Window.Resources>

<Grid Background="#FFEFEDDF">
    <Grid.RowDefinitions>
        <RowDefinition Height=".5*"/>
        <RowDefinition Height=".5*"/>
        <RowDefinition Height="4*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="5*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width=".2*"/>
        <ColumnDefinition Width=".7*"/>
        <ColumnDefinition Width=".7*"/>
        <ColumnDefinition Width=".7*"/>
        <ColumnDefinition Width=".5*"/>
        <ColumnDefinition Width="4*"/>
        <ColumnDefinition Width=".1*"/>
    </Grid.ColumnDefinitions>
    <Calendar x:Name="cDatePicker" Grid.Column="1" Grid.Row="2" Grid.RowSpan="2" Grid.ColumnSpan="2" SelectedDatesChanged="cDatePicker_SelectedDatesChanged" />
    <Label Content="Start Date:" Grid.Column="1" Grid.Row="4" Margin="5"/>
    <TextBox x:Name="txtStartDate" Grid.Column="2" Grid.Row="4" Margin="5" VerticalContentAlignment="Center" />
    <Label Content="End Date:" Grid.Column="1" Grid.Row="5" Margin="5"/>
    <TextBox x:Name="txtEndDate" Grid.Column="2" Grid.Row="5" Margin="5" VerticalContentAlignment="Center"/>
    <Label Content="Supplier Number:" Grid.Column="1" Grid.Row="6" Margin="5"/>
    <TextBox x:Name="txtCustomerNumber" Grid.Column="2" Grid.Row="6" Margin="5" VerticalContentAlignment="Center" TabIndex="1" />
    <Button x:Name="btnShowRport" Content="View Report" Grid.Column="1" Grid.Row="8" Margin="0,0,10,0"  Click="btnShowRport_Click" IsDefault="True" />
    <Button x:Name="btnPrintReport" Content=" Print Report" Grid.Column="2" Grid.Row="8" Margin="10,0,0,0"  Click="btnPrintReport_Click" />
    <my:CrystalReportsViewer  x:Name="crReportViewer" Grid.Column="3" Grid.RowSpan="10" HorizontalAlignment="Center" VerticalAlignment="Center" 
                              Height="656" Width="845" Margin="94,-7,62,12" ToggleSidePanel="None" Panel.ZIndex="0" Grid.ColumnSpan="3" 
                              ShowPrintButton="False" ShowRefreshButton="False" ShowSearchTextButton="False" ShowToggleSidePanelButton="True"
                              ShowToolbar="True" ShowNextPageButton="True" ShowGoToPageButton="True" ShowExportButton="False" 
                              ShowCopyButton="False" SnapsToDevicePixels="True" ShowLogo="False" ShowPrevPageButton="True" 
                              ShowStatusbar="True" />
</Grid>

Thanks


Little late, but when you get a null reference exception like this, it can be misleading. The inner exception may be null (was in my case.)

The way I discovered the issue was to enable first chance exceptions in VS 2010.

Goto Debug -> Exceptions then check all the boxes.


You need to look at the inner exception. When initialcomponent is called it can fire off other code which must be causing an exception. The inner exception should give you all the information you need. Note that it is possible that the inner exception will have an inner exception itself. Modify your app to write all these to a file or the clipboard or something.


I had this problem twice, and in both cases it was my lack of knowledge of patterns that are healthy for WPF programming.

In both cases, there wasn't an inner exception, and there was no code or whatsoever to follow and debug.

It happened that there was a Binding pointing to a Path that didn't exist in the DataContext object. It's very hard to find the problem, but I suggest to go looking for every Binding you have and the respective data context, having in mind that you might have a context coming from a parent upstream.

See this example (true case):

  • I migrated an application from Windows Forms. Since I was working with a Chart I had to keep using some System.Windows.Forms components and their philosophy.
  • I set the DataContext for the panel showing the chart programmatically with MyChartPanel.DataContext = ChartControllerInstance
  • So far so good, the program worked pretty well, the bindings were all ok
  • Later, I used the XAML way of adding a DataContext to the Window, for trying to have a viewmodel.
  • Then the bug started.

What happened?

Since the chart data context was not set in XAML, but only via code, the window data context was propagated to all its children.

All those chart bindings (which in the first version didn't have a context at all) now had a context: the window view model, which didn't have anything needed for the chart.

The null reference appeared because those binding found a context, but not their path inside the context.

The solution? I had to explicitly use a DataContext={Binding null} in the chart panel, to prevent its bindings from searching inside the window context. This doesn't raise exceptions, and later in the code the chart context is set programmatically, and all works well.

I know this is a terrible bad practice, but I'm still a newbie in WPF and didn't figure out a better way yet.


Issue disappeared when I rename/remove the old assemblies at GAC (C:\Windows\Microsoft.NET\assembly\GAC_MSIL => GAC location for .NET framework 4.0 or higher) location.


This can happen if you don't call the InitializeComponent(); within the constructor

EG

public partial class LogExaminer : Window
{
    public LogExaminer()
    {
        InitializeComponent();    //comment out this to see the error
    }
}


In Xamarin you can enable Compiled Bindings. In this case, binding issues will be caught by the compiler.

Consider enabling this feature for your projects, it's a time saver. I saw some plugins for WPF.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜