wpf--Additional events (attached event)

Source: Internet
Author: User

3.3 Events also attached------additional events in layman's

Another event in the WPF event system is called an attached event (attached), in short, it is a routed event. "Then why do you have a new name?" "You may ask.

"No Color Phoenix wings, touches your heart", this is a true portrayal of the attached event host. How do you explain it? Let's see what classes have additional events:

    • Binding class: Sourceupdated event, targetupdated event
    • Mouse classes: MouseEnter events, MouseLeave events, MouseDown events, MouseUp events, and more
    • Keyboard class: KeyDown event, KeyUp event, etc.

Compare the classes that have routed events, such as Button, Slider, TextBox ... Did you find anything wrong? It turns out that the host of routed events is an interface element that has visual entities, while attached events do not have the ability to display them on the user interface. In other words, the host of the attached event does not have an interface rendering function for this pair of "flying wings", but the same can be used to communicate with other objects using the attached event.

Understanding the principle of additional events, let's write an example. The logic I want to implement is this: Design a class named student that fires a routed event if the value of the student instance's Name property changes, and I use the interface element to capture the event.

The code for this class is as follows:

1  Public classStudent2 {3     //declaring and defining routed events4      Public Static ReadOnlyRoutedEvent namechangedevent =eventmanager.registerroutedevent5("namechanged", Routingstrategy.bubble,typeof(Routedeventhandler),typeof(Student));6 7      Public intId {Get;Set; }8      Public stringName {Get;Set; } 9}

To design a simple interface:

1<window x:class="Wpfapplication1.window1"2xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"3xmlns:x="Http://schemas.microsoft.com/winfx/2006/xaml"title="attached Event"4height=" $"Width=" $">5<grid x:name="Gridmain">6<button x:name="button1"Content="OK"Width=" the"height=" the"7click="Button_Click"/>8</Grid>9</Window>

The following table code is as follows:

1  Public Partial classWindow1:window2 {3      PublicWindow1 ()4     {5 InitializeComponent ();6 7         //Add a routed event listener to the outer grid8          This. Gridmain.addhandler (9 Student.namechangedevent,Ten             NewRoutedeventhandler ( This. Studentnamechangedhandler)); One     } A  -     //Click event handler -     Private voidButton_Click (Objectsender, RoutedEventArgs e) the     { -Student stu =NewStudent () {Id =101, Name ="Tim" }; -Stu. Name ="Tom"; -         //preparing event messages and sending routed events +RoutedEventArgs arg =NewRoutedEventArgs (Student.namechangedevent, Stu); -          This. Button1. RaiseEvent (ARG); +     } A  at     //The grid captures the processor after the Namechangedevent -     Private voidStudentnamechangedhandler (Objectsender, RoutedEventArgs e) -     { -MessageBox.Show ((E.originalsource asStudent). Id.tostring ()); -     } -}

In the background code, the Button_Click method is triggered when the only button on the interface is clicked. It is important to note that because student is not a derived class of UIElement, it does not have the RaiseEvent method and has to "borrow" the RaiseEvent method of the button in order to send a routed event. In the form's constructor, I added a listen to student.namechangedevnet for the grid element-no difference to adding a listen to a routed event. The grid displays the ID of the event message source (an student instance) after it snaps to the routed event.

Run the program and click on the button to effect

In theory, the student class now has an attached event, but Microsoft's official documentation convention is to add a CLR wrapper for this additional event so that the XAML editor can identify and intelligently hint. Unfortunately, the student class is not derived from UIElement and therefore does not have two methods of AddHandler and RemoveHandler, Therefore, you cannot use CLR properties as wrappers (because the Add and remove branches of the CLR property wrapper call the current object's AddHandler and RemoveHandler, respectively). Microsoft rules:

    • The wrapper for adding an additional event listener for the target UI element is a public static method named Add*handler, which represents the event name (consistent with the name when registering the event). This method receives two parameters, the first parameter is the listener for the event (type DependencyObject), and the second parameter is the processor of the event (Routedeventhandler delegate type).
    • The wrapper that unlocks the UI element to the attached event is the public static method named Remove*handler, and the asterisk is the event name, and the parameter is consistent with Add*handler.

By specification, the student class is upgraded to this:

1  Public classStudent2 {3     //declaring and defining routed events4      Public Static ReadOnlyRoutedEvent namechangedevent =eventmanager.registerroutedevent5("namechanged", Routingstrategy.bubble,typeof(Routedeventhandler),typeof(Student));6 7     //adding routed event listeners for interface elements8      Public Static voidAddnamechangedhandler (DependencyObject D, Routedeventhandler h)9     {TenUIElement E = d asUIElement; One         if(E! =NULL) A         { - E.addhandler (Student.namechangedevent, h); -         } the     } -  -     //Remove Listen -      Public Static voidRemovenamechangedhandler (DependencyObject D, Routedeventhandler h) +     { -UIElement E = d asUIElement; +         if(E! =NULL) A         { at E.removehandler (Student.namechangedevent, h); -         } -     } -  -      Public intId {Get;Set; } -      Public stringName {Get;Set; } in}

The original code also needs to make the corresponding changes (only to add the event to listen to one place need to change):

 1  public   Window1 ()  2  3   InitializeComponent ();  4  //   add routed event listeners to the outer grid  6   Student.addnamechangedhandler ( 7  thi s  .gridmain,  8  new  Routedeventhandler (. Studentnamechangedhandler));  9 } 

Now let's take a closer look at the "attach" of the attached event. Specifically, the UIElement class is the watershed between the routed event host and the attached event host, not only because of the ability to display on the interface starting from the UIElement class, but also because of the RaiseEvent, Addhander and RemoveHandler These methods are also defined in the UIElement class. Therefore, if a routed event is registered in a non-UIElement derived class, the instance of the class cannot fire itself (Raise) This routed event also cannot listen for this routed event on its own, only the excitation of the event "attaches" to an object with RaiseEvent method, The RaiseEvent method of this object is used to send the event, and the listener task of the event can only be given to other objects. In summary, the attached event can only be considered a use of routed events rather than a new concept, and perhaps one day Microsoft will revoke the concept of additional events.

Finally, share some practical work experience.

First, like Button.Click these routed events, because the event host is an interface element, itself is a node in the UI tree, so the first stop when routing event routing is the event's activator. The attached event host is not a derived class of UIElement, so it cannot appear on a node in the UI tree, and the triggering of an attached event is implemented with UI elements, so the first station that attaches the event route is the element that fires it.

Second, it is very rare to define additional events in student classes that are related to business logic and are generally defined in global helper classes such as binding, Mouse, keyboard. What if an object that requires a business logic class can send a way out by an event? We don't have binding! If the program architecture is well designed (using a data-driven UI), then the business logic must be associated with the UI element using a binding object. Once the object associated with the business logic implements the INotifyPropertyChanged interface and the Notifyonsourceupdated property of the binding object is set to True, The binding fires its sourceupdated attached event, which is routed on the UI element tree and captured by the listener.

Reprint: http://blog.csdn.net/FantasiaX/article/details/4575968

Related: http://blog.csdn.net/fwj380891124/article/details/8139260

wpf--Additional events (attached event)

Related Article

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.