How WPF controls the popup of the right-click menu ContextMenu

Source: Internet
Author: User

In specific to do some projects, sometimes need to left click on a node, and then right click on the node when the right menu pops up, so directly right click on the need to disable the right button menu, here, for example, we added a ContextMenu to the grid, But we need to set a bool variable isselected, and when we execute into the MouseLeftButtonDown event, we can set the isselected to True, Then add the previewmouserightbuttonup= "Onmouserightbuttonup" (tunnel event routing) event in the grid or the Mouserightbuttonup (bubbling event routing) event, both of which can be , but do not add under <Grid.ContextMenu/> and its child nodes, this is described later, and then execute the following code in the main program:

private void Onmouserightbuttonup (Object Sender,mousebuttoneventargs e)

{

if (isselected==true)

{

Make a message available for delivery

E.handled=false;

}

Else

{

E.handled=true;

}

Isselected=false;

}

So when we left click on a node, and then click on the right button to pop ContextMenu, here we need to correctly understand the meaning of handled, handled to mark the routed event as a processed value. If the value of Handled is true, you can prevent most handlers on the event routing path from processing the same event again. This is very useful in actual event handling, because this layer of WPF nesting UI design ideas makes an event, For example, Uielement.mouseleftbuttondown is triggered on many elements, depending on the type of event, which can be triggered by bubbling or tunneling, but in fact only one element eventually executes the event, and if an element has already performed the event, it will handled is set to true so that the event does not go down or on the road, it is important to set the handled to False if you want the event to continue routing, which makes sense when you refer to a blog post written by someone else.

Read "WPF advanced Programming" to see the uploading and posting of events. Here's an example:

Front Code:

<window x:class= "Tunnelingbubbling.window1"    xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/ Presentation "    xmlns:x=" Http://schemas.microsoft.com/winfx/2006/xaml "    title=" Window1 ">    <grid Mouseleftbuttondown= "Grid_mouseleftbuttondown"     previewmouseleftbuttondown= "Grid_previewmouseleftbuttondown "     width=" 313 "height=" 271 "name=" Mygrid ">        <button previewmouseleftbuttondown=" Button_ Previewmouseleftbuttondown "         mouseleftbuttondown=" Button_mouseleftbuttondown "click=" Button_Click "Name=" Btngo ">            <textbox name=" TextBox1 "width=" 173 "height=" mouseleftbuttondown= "textbox1_"            MouseLeftButtonDown "             previewmouseleftbuttondown=" Textbox1_previewmouseleftbuttondown ">            </ textbox>        </Button>    </Grid></Window>

The Previewmouseleftbuttondown and MouseLeftButtonDown events are defined for Grid,button,textbox, respectively, and the click event defined for the Button.

The background code is as follows:

   Public partial class Window1:window {public Window1 () {InitializeComponent (); private void Grid_previewmouseleftbuttondown (object sender, MouseButtonEventArgs e) {Debug.writel       INE ("Grid_previewmouseleftbuttondown"); private void Button_previewmouseleftbuttondown (object sender, MouseButtonEventArgs e) {Debug.writ       Eline ("Button_previewmouseleftbuttondown"); private void Textbox1_previewmouseleftbuttondown (object sender, MouseButtonEventArgs e) {DEBUG.WR       Iteline ("Textbox1_previewmouseleftbuttondown"); } private void Grid_mouseleftbuttondown (object sender, MouseButtonEventArgs e) {Debug.WriteLine ("Gr       Id_mouseleftbuttondown ");       } private void Button_Click (object sender, RoutedEventArgs e) {Debug.WriteLine ("Button_Click");  private void Textbox1_mouseleftbuttondown (object sender, MouseButtonEventArgs e)     {Debug.WriteLine ("Textbox1_mouseleftbuttondown"); } private void Button_mouseleftbuttondown (object sender, MouseButtonEventArgs e) {Debug.WriteLine ("       Button_mouseleftbuttondown "); }   }

However, at the time of execution, the MouseLeftButtonDown event always fails to fire. Looked at some information before I knew it was a matter of design in principle. After capturing the MouseLeftButtonDown event, the control sets the event's "Handled" to True, which is used in event routing, and when a control gets a routedevent, it detects whether Handled is true, True to ignore the event.

Also, the Click event of the control itself is equivalent to dropping the MouseLeftButtonDown event suppression (supress) and converting it into a click event. Therefore, if you must use this event, you need to explicitly increase the event by using the UIElement AddHandler method in the initialized function.

--------------------------------------------------------------------------------------------------

---------Method Description:---------------------------------------------------------------------------------

Uielement.addhandler method (RoutedEvent, Delegate, Boolean)

Adds a routed event handler for the specified routed event and adds the handler to the handler collection for the current element. When HandledEventsToo is specified as true, the provided handler can be called for routed events that have been marked as handled by other elements during the event routing process.

Parameter description:

HandledEventsToo type: System.::. Boolean

If true, the handler is registered, even if the routed event is marked handled in its event data, and if False, the handler is registered with the default condition, that is, the handler is not called when the routed event is marked as handled.

The default value is False.

--------------------------------------------------------------------------------------------------

The modified program code is as follows:

     Public Window1 ()      {          InitializeComponent ();          Mygrid. AddHandler (Grid.mouseleftbuttondownevent, New Mousebuttoneventhandler (this. Grid_mouseleftbuttondown), true);          Btngo.addhandler (Button.mouseleftbuttondownevent, New Mousebuttoneventhandler (this. Button_mouseleftbuttondown), true);          Textbox1.addhandler (Textbox.mouseleftbuttondownevent, New Mousebuttoneventhandler (this.textbox1_ MouseLeftButtonDown), True);      }

Run again, the call succeeds.

The order in which the events are executed is:

Order

Control

Event

Event Type

1

Grid Previewmouseleftbuttondown

Next Pass

2

Button Previewmouseleftbuttondown

Next Pass

3

Textbox Previewmouseleftbuttondown

Next Pass

4

Textbox MouseLeftButtonDown

Upload

5

Button MouseLeftButtonDown

Upload

6

Grid MouseLeftButtonDown

Upload

If you click the button, the order in which the events are executed is:

Order

Control

Event

Event Type

1

Grid Previewmouseleftbuttondown

Next Pass

2

Button Previewmouseleftbuttondown

Next Pass

3

Button MouseLeftButtonDown

Upload

4

Grid MouseLeftButtonDown

Upload

5

Button Click

Finally, add one point:

In the event handler, you can cancel the event handling to find the source element of the event

For example, in the following code:

private void Button_previewmouseleftbuttondown (object sender, MouseButtonEventArgs e)       {           Debug.WriteLine (" Button_previewmouseleftbuttondown ");          E.handled = true;          Button MyButton = E.source as Button;       }

1. Cancel event handling: Set e.handled = true;

2. Find the source element in the event handler: E.source passes an actual object instance that can be cast to the System.Windows.Controls.Button type.

With this variable, you can access all the local properties, methods, and events provided by this control.

How WPF controls the popup of the right-click menu ContextMenu

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.