以编程方式添加WP7 ContextMenu [英] Adding WP7 ContextMenu programmatically

查看:83
本文介绍了以编程方式添加WP7 ContextMenu的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在页面上动态加载元素(读取XML文件的内容)。动态内容被加载到 StackPanel 中。内容的每个元素都包含一个 TextBlock 和另一个UI元素,因此我为每一对创建了一个新的 StackPanel 然后将其添加到父 StackPanel 中。代码如下所示:

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

我想为此添加 ContextMenu StackPanel sp ,而不是 parentSP );根据从文件中读取的某些参数,它可能是2个不同的上下文菜单之一。我尝试了以下操作,但不起作用:

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

如何向 StackPanel 以编程方式?

还有,还有解决这个问题的更好方法吗?也许通过在XAML资源部分中存储2种不同类型的上下文菜单并根据需要添加它们?我尝试通过将上下文菜单添加到父级的 StackPanel.Resource 部分中来执行此操作,但是收到一条错误消息:一个属性元素不能是另一个属性元素的直接子代

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"

预先感谢您的帮助

推荐答案

ContextMenuService.SetContextMenu(sp, cm);

这篇关于以编程方式添加WP7 ContextMenu的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆