Question

I tried a few things about adding my own created user control element to listbox or stackpanel, but instead of gaining any success, it causes a NullReferenceException and I have no idea why ...

my user control is looking like that:

public partial class ShiftInformationItem : UserControl
{
    public ShiftInformationItem()
    {
        InitializeComponent();
    }
}

and the xaml:

<Grid>
    <LabelContent="Benutzername:" />
    <Label Content="01.03.2014 14:19" />
    <TextBox Text="Eintrag ..." />
    <Expander Header="Comments (0)">
        <Grid Background="#FFE5E5E5"/>
    </Expander>
</Grid>

Inside the main window I can add it in a listbox or a stackpanel without any Trouble:

<ListBox>
     <controls:ShiftInformationItem  />
</ListBox>

or:

<StackPanel Name="ShiftInformationPanel">
     <controls:ShiftInformationItem  />
</StackPanel>

But when I try to add it with C#:

ShiftInformationList.Items.Add(new ShiftInformationItem());
ShiftInformationPanel.Children.Add(new ShiftInformationItem());

it causes the NullReferenceException and says the object I want to add is null.

Does anybody can explain me why?

Im very thankful for all well meaned and helpful answers in advance!

UPDATE:

public partial class HoBusReceptionMain : Window
{
    public HoBusReceptionMain()
    {
        InitializeComponent();
    }

    private void RibbonWin_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        RibbonTab r = (RibbonTab)e.AddedItems[0];
        switch (r.Header.ToString())
        {
            case "Shift Information":
                InitializeShiftInformationTab();
                break;
            default:
                MessageBox.Show(e.AddedItems[0].ToString());
                break;
        }
    }

    private void InitializeShiftInformationTab()
    {
        //here I want to add the new ShiftInformationItem
    }

}

UPDATE 2:

Thanks all comments, it Shows up, that my list || Panel is null ... But both is included in the main window (above HoBusReceptionMain)

I use Ribbons in my application, and when a ribbon tab is selected or loaded the RibbonWin_SelectionChanged Event is fired ... The list or Panel defined below the ribbon definitions

Was it helpful?

Solution

I suspect you are adding that before InitializeComponent() gets called.

Move the code of adding below InitializeComponent() and it will work like it did from XAML. Issue is controls were not initialized before InitializeComponent() gets called and hence resulting in NullReferenceException.

public MainWindow()
{
    InitializeComponent();
    ShiftInformationList.Items.Add(new ShiftInformationItem());
    ShiftInformationPanel.Children.Add(new ShiftInformationItem());
    // ShiftInformationPanel is null here
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top