Search code examples
c#wpfrepository-patternobject-reference

object reference is not set to an instance of an object repository


I am getting an XAMLParseException that is really covering up another exception. Here is part of the stacktrace:
Message=Object reference not set to an instance of an object.
Source=AssignmentOrganizer
StackTrace:
at AssignmentOrganizer.MainWindow..ctor() in C:\Users\Mohit\Documents\Visual Studio 2010 \Projects\AssignmentOrganizer\AssignmentOrganizer\MainWindow.xaml.cs:line 29

Here is line 29:

lvwMain.ItemsSource = _assignmentRepo.ListAssignments();

Where lvwMain is a ListView and _assignmentsRepo is an IAssignmentRepository declared like:

IAssignmentRepository _assignmentRepo; 

That is where the error occurs. I am using the repository pattern Anyone willing to take a guess?
Here is my XAML:

<Window x:Class="AssignmentOrganizer.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit"
    Title="MainWindow" Height="518" Width="755">
<DockPanel>
    <Menu DockPanel.Dock="Top">

    </Menu>
    <ToolBar DockPanel.Dock="Top">

    </ToolBar>
    <StatusBar DockPanel.Dock="Bottom">

    </StatusBar>
    <Grid DockPanel.Dock="Left" Width="150">
        <Grid.RowDefinitions>
            <RowDefinition Height="259*" />
            <RowDefinition Height="259*" />
        </Grid.RowDefinitions>
    </Grid>
    <Grid DockPanel.Dock="Right" Width="150">

    </Grid>
    <Grid>
        <ListView x:Name="lvwMain">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Title"  Width="125" />
                    <GridViewColumn Header="Due"  Width="75" />
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
</DockPanel>


Solution

  • In your constructor, make sure you put the InitializeComponent call before doing any other constructor logic.

    public MainWindow()
    {
        // Do this first.
        InitializeComponent();
    
        // Now do the rest of the constructor.
        ...
        lvwMain.ItemsSource = _assignmentRepo.ListAssignments();
        ...
    }