简体   繁体   中英

Context Menu in WPF without XAML

I am trying to design an application with 256 button inside. These buttons are added by using "for" loop in c#, so they are not in the XAML code. 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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