简体   繁体   English

没有XAML的WPF中的上下文菜单

[英]Context Menu in WPF without XAML

I am trying to design an application with 256 button inside. 我正在尝试设计一个带有256个按钮的应用程序。 These buttons are added by using "for" loop in c#, so they are not in the XAML code. 这些按钮是通过在c#中使用“ for”循环添加的,因此它们不在XAML代码中。 My problem is that - I don't know how to add a Context Menu to such a button. 我的问题是-我不知道如何向这样的按钮添加上下文菜单。 The context menu should open when clicking right mouse button on particular button. 在特定按钮上单击鼠标右键时,上下文菜单应打开。 Then I want to be able to change some variable in code, when selecting some of the context menu item. 然后,我希望能够在选择某些上下文菜单项时更改代码中的某些变量。

My code for adding buttons is following: 我添加按钮的代码如下:

public MainWindow()
{
    InitializeComponent();

    int num = number(3);

    for(int i =0; i<(num*num); i++)
    {
        //i want initialize the context menu here 
        Button button = new Button();

        button.Name = "Butt" + counter;

        button.Content = "New";

        counter++;
        button.Height = 35;
        button.Width = 35;
        button.Click += new RoutedEventHandler(NewButton_Click);
        wp.Children.Add(button); // Wrap Panel where buttons displayed
    }}

You can create a context menu like this: 您可以创建一个上下文菜单,如下所示:

 ContextMenu c = new ContextMenu();
 MenuItem i1 = new MenuItem();
 i1.Header = "Some Header";
 i1.Click += i1_Click;
 c.Items.Add(i1);

and attach it to a button like this: 并将其附加到这样的按钮上:

 button.ContextMenu = c;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM