CodeBehind中的动态ContextMenu [英] Dynamic ContextMenu In CodeBehind

查看:71
本文介绍了CodeBehind中的动态ContextMenu的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想为我动态创建的多个对象添加ContextMenu,但是
我发现的唯一方法是在运行时像这样创建ContextMenu:

I just want to add ContextMenu for several objects that I create dynamically, but The only way I found is to create ContextMenu in runtime like this:

ContextMenu pMenu = new ContextMenu();
MenuItem item1  = new MenuItem();
MenuItem item2  = new MenuItem();

//I have about 10 items
//...
item1.Header = "item1";
item1.Click += new RoutedEventHandler(item1_Click);
pMenu.Items.Add(item1);

item2.Header = "item2";
item2.Click += new RoutedEventHandler(item2_Click);
pMenu.Items.Add(item2);

//and so on

它在WinForms I中有效无需编写任何代码,就能将ContextMenuStrip组件拖放到我的表单中并快速定义项目和事件。在WPF中可以吗?

It works, however, in WinForms I was able to drop ContextMenuStrip component to my form and define items and events very quickly w/o writing any code. Is it possible in WPF?

推荐答案

您可以在以下位置定义 ContextMenu 资源并将其绑定到所需的任何控件。检查一下:

You can define your ContextMenu in resources and bind it to any control you needed. Check this out:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Window.Resources>
        <ContextMenu x:Key="MyContextMenu">
            <MenuItem Header="Send" />
        </ContextMenu>
    </Window.Resources>
    <Grid>
        <Button Name="a_button"
            ContextMenu="{StaticResource MyContextMenu}" >
        </Button>
    </Grid>
</Window>

这篇关于CodeBehind中的动态ContextMenu的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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