Awarious OfficePortal - HRMS Application

WPF attached event purpose

+1 vote
asked Jul 8, 2013 in WPF by Rajkumar

I am not able to understand the purpose of wpf attached events. Why do we need that and how it is internally working. Please post me some clear information or give me some reference.


1 Answer

+1 vote
answered Jul 8, 2013 by Aadhira (1,215 points)
selected Jul 9, 2013 by administrator
Best answer

Attached events are used to handle the event from a different control mostly from parent control rather than from the same control which has that event. This functionality is possible only because of bubbling and tunneling event concepts.

Understanding bubbling and tunneling events

For example, if you have 2 button controls inside the stack panel. If both of that controls are doing some functionality and you want to handle the click event of those 2 buttons from a single method. In that case you can use the click event of the ButtonBase class as an attached event in the StackPanel and raise the event when any one button got clicked. Notice one thing that, there is not click event in stack panel. Still we are able to handle the button click event from stack panel only because or bubbling and tunneling routed events. Otherwise the click event of the button will not come to the stack panel and we cannot handle it.
Below example shows how to use attached event.

        <StackPanel ButtonBase.Click="Attached_ButtonClick">
            <Button Content="Yes" Height="23" Name="btnYes" Width="75" />
             <Button Content="No" Height="23" Name="btnNo" Width="75" />

private void Attached_ButtonClick(object sender, RoutedEventArgs e)
            Button source = (Button)e.Source;
            if (source.Name == "btnYes")
                Debug.WriteLine("'Yes' button clicked");
             else if (source.Name == "btnNo")
                Debug.WriteLine("'No' button clicked");

'Yes' button clicked
'No' button clicked

Your answer


Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.
site design / logo / content © 2013 - 2019