Adding WP7 ContextMenu programmatically

I load elements on the page dynamically (reading the contents of an XML file). Dynamic content is loaded into the StackPanel . Each content element consists of a TextBlock and another user interface element, so for each pair I create a new StackPanel , which is then added to the parent StackPanel . The code is as follows:

 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 ); 

I want to add ContextMenu to this StackPanel ( sp , not parentSP ); depending on some parameters read from the file, it can be one of two different context menus. I tried the following, but it does not work:

  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 ); 

How to add a program menu to the StackPanel context menu?

Also, is there a better way to solve this problem? Maybe by storing two different types of context menus in the XAML resource section and adding them as needed? I tried to do this by adding a context menu to the parent section of StackPanel.Resource , but I got an error: "Property element cannot be a direct child of another property element"

Thank you in advance for your help.

+4
source share
1 answer
 ContextMenuService.SetContextMenu(sp, cm); 
+9
source

Source: https://habr.com/ru/post/1333537/


All Articles