问题
I'm loading elements on a page dynamically (reading the contents of an XML file). The dynamic content is loaded into a StackPanel
. Each element of the content consists of a TextBlock
and one other UI element, so for each pair I create a new StackPanel
which is then added to the parent StackPanel
. The code looks like this:
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 a ContextMenu
to this StackPanel
(sp
, not parentSP
); 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:
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 do I add a context menu to the StackPanel
programmatically?
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 StackPanel.Resource
section but got an error saying "A property element cannot be the direct child of another property element"
Thanks in advance for your help
回答1:
ContextMenuService.SetContextMenu(sp, cm);
来源:https://stackoverflow.com/questions/4543654/adding-wp7-contextmenu-programmatically