title: C# WPF: Adding custom Usercontrol to Stackpanel
body: <p>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 <strong>NullReferenceException</strong> and I have no idea why ...</p>
  
  <p>my user control is looking like that:</p>
  
  <pre><code>public partial class ShiftInformationItem : UserControl
  {
      public ShiftInformationItem()
      {
          InitializeComponent();
      }
  }
  </code></pre>
  
  <p>and the xaml:</p>
  
  <pre><code>&lt;Grid&gt;
      &lt;LabelContent="Benutzername:" /&gt;
      &lt;Label Content="01.03.2014 14:19" /&gt;
      &lt;TextBox Text="Eintrag ..." /&gt;
      &lt;Expander Header="Comments (0)"&gt;
          &lt;Grid Background="#FFE5E5E5"/&gt;
      &lt;/Expander&gt;
  &lt;/Grid&gt;
  </code></pre>
  
  <p>Inside the main window I can add it in a listbox or a stackpanel without any Trouble:</p>
  
  <pre><code>&lt;ListBox&gt;
       &lt;controls:ShiftInformationItem  /&gt;
  &lt;/ListBox&gt;
  </code></pre>
  
  <p>or:</p>
  
  <pre><code>&lt;StackPanel Name="ShiftInformationPanel"&gt;
       &lt;controls:ShiftInformationItem  /&gt;
  &lt;/StackPanel&gt;
  </code></pre>
  
  <p>But when I try to add it with C#:</p>
  
  <pre><code>ShiftInformationList.Items.Add(new ShiftInformationItem());
  ShiftInformationPanel.Children.Add(new ShiftInformationItem());
  </code></pre>
  
  <p>it causes the <strong>NullReferenceException</strong> and says the object I want to add is null.</p>
  
  <p>Does anybody can explain me why?</p>
  
  <p>Im very thankful for all well meaned and helpful answers in advance!</p>
  
  <p>UPDATE:</p>
  
  <pre><code>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
      }
  
  }
  </code></pre>
  
  <p>UPDATE 2:</p>
  
  <p>Thanks all comments, it Shows up, that my list || Panel is null ... But both is included in the main window (above HoBusReceptionMain)</p>
  
  <p>I use Ribbons in my application, and when a ribbon tab is selected or loaded the <strong>RibbonWin_SelectionChanged</strong> Event is fired ... The list or Panel defined below the ribbon definitions</p>