Question

I have a problem finding the right Eventhandler for my ContextMenu. Note that this isn't a ContextMenuStrip. I have declared the ContextMenu as follows:

public void button_MouseRightButtonDown(object sender, MouseButtonEventArgs e)//add a context menu to buttons
{
   Button button = sender as Button;
    menu = new ContextMenu();
    menu.Items.Add(new MenuItem() { Header = "Delete" });
    button.ContextMenu = menu;
    menu.Closed += button_DeleteButtonClicked;//find the right event

}

Example:

http://puu.sh/6Jymf.jpg http://puu.sh/6Jymf.jpg

And then, the handler (which now is wrong, .Closed fires the event when the menu is closed):

private void button_DeleteButtonClicked(object sender, RoutedEventArgs e)//delete bookmark
{
    Button button = ((ContextMenu)sender).PlacementTarget as Button;
    string line_to_delete = button.ToString().Replace("System.Windows.Controls.Button: ", "");
    string[] lines = File.ReadAllLines(@"bookmarks.txt");
    File.WriteAllText(@"bookmarks.txt", String.Empty);
    for (int i = 0; i < lines.Length; i++)
    {
        if (lines[i] != line_to_delete)
        {
            using (StreamWriter wr = File.AppendText(@"bookmarks.txt"))
            {
                wr.WriteLine(lines[i]);
            }
        }
    }
}

So basically I'm looking for a handler that fires the event when "Delete" is pressed, not when the ContextMenu is closed. My guess is that my declare on the first piece of code is wrong but I can't seem to figure it out.

Was it helpful?

Solution

You have to bind the Click event of the MenuItem. It's probably going to end up looking like this (I don't have the means of testing this code right now, but it should be close):

// (old) ...
menu.Items.Add(new MenuItem() { Header = "Delete" });
// ...

// (tweak to) ...
var deleteMenuItem = new MenuItem() { Header = "Delete" };
deleteMenuItem.Click += button_DeleteButtonClicked;
menu.Items.Add(deleteMenuItem);
// no need to bind menu.Close for this
// ...

Binding ContextMenu.Close is useful if you want to perform some code no matter what the user chose, but it doesn't look like it's useful to you in this particular scenario.

The handler method should also be adjusted, of course, to accomodate the different sender:

// ...
Button button = ((ContextMenu)((MenuItem)sender).Parent).PlacementTarget as Button;
// .SourceControl could also be a viable alternative to .PlacementTarget
// ...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top