title: Adding WP7 ContextMenu programmatically
body: <p>I'm loading elements on a page dynamically (reading the contents of an XML file). The dynamic content is loaded into a <code>StackPanel</code>. Each element of the content consists of a <code>TextBlock</code> and one other UI element, so for each pair I create a new <code>StackPanel</code> which is then added to the parent <code>StackPanel</code>. The code looks like this:</p>
  
  <pre><code>TextBlock header = new TextBlock() {
          Text = "Heading 1",
          HorizontalAlignment = HorizontalAlignment.Stretch,
          VerticalAlignment = VerticalAlignment.Top,
          Foreground = (SolidColorBrush)Application.Current.Resources["PhoneAccentBrush"],
        };
  TextBox item = new TextBox() {
          HorizontalAlignment = HorizontalAlignment.Stretch,
          VerticalAlignment = VerticalAlignment.Top,
        };
  StackPanel sp = new StackPanel();
  sp.Children.Add( header );
  sp.Children.Add( item );
  
  parentSP.Children.Add( sp );
  </code></pre>
  
  <p>I want to add a <code>ContextMenu</code> to this <code>StackPanel</code> (<code>sp</code>, not <code>parentSP</code>); depending on some parameters read from the file it could be one of 2 different context menus. I tried the following but it is not working:</p>
  
  <pre><code>    ContextMenu cm = new ContextMenu();
      RoutedEventHandler clickHandler = new RoutedEventHandler( OnContextMenuClicked );
  
      // Add "edit" entry
      MenuItem menuItem = new MenuItem() {
        Header = "edit",
        Tag = "edit",
      };
  
      menuItem.Click += clickHandler;
      cm.Items.Add( menuItem );
  
      // Add "delete" entry
      menuItem = new MenuItem() {
        Header = "delete",
        Tag = "delete",
      };
  
      menuItem.Click += clickHandler;
      cm.Items.Add( menuItem );
  
      parentSP.Children.Add( cm );
  </code></pre>
  
  <p>How do I add a context menu to the <code>StackPanel</code> programmatically? </p>
  
  <p>Also, is there a better way to solve this problem? Maybe by storing the 2 different types of context menus in a XAML resources section and adding them as needed? I tried doing this by adding the context menus to the parent's <code>StackPanel.Resource</code> section but got an error saying "A property element cannot be the direct child of another property element"</p>
  
  <p>Thanks in advance for your help</p>