Wpf how to send custom event (or RoutedEvent) from parent to all childs that implement the handler.
Hi guys, as the title says, i want to send an event from parent control to all childrens that implement the handler of that type of event. The child itself is a UserControl, which then the UserControl will handle it.
In this project, i am using an MVVM pattern. I have read a little bit about RoutedEvent and some related terminologies such as direct, bubbling, and tunneling event (and still don't know how to use that knowledge, just ignore if it doesn't affect this question).
Let's say that i have a button that when clicked, it will raise an event (or notify somehow) the parent that the user wants to open a file. Then, the parent will send this event to all of its childrens that implement the handler (similar to tunneling routed event).
If possible, i don't want to manually set every kind of children types (in the definition of the code-behind) to listen to the specific parent like finding the parent control then listen to the event of that parent control (e.g Parent.EventName += this.HandlerName).
In WPF, If i'm not wrongly understood, the children should automatically listen to the event when we declaring the control in XAML and setting the attribute SomeEventName="HandlerMethodName" right? e.g Click="HandlerMethodName".
So again, how do i automatically make the child to listen to specific parent event (any parent, as long the event type matches), then the parent will send the event to all childs that implement the handler?
Sorry if my message is too long. I just want to be as clear as possible of what i want and what i have know
Example project:
Below screenshot is a very simple project that has a button and a UserControl. When the user clicked on the button, the button raised the parent event (for example the window itself). Then i want the UserControl to listen to this parent event. The UserControl will handle this event, and change the TextBlock content based on the event argument.
8 Replies
the GUI
GUI declaration of this window
MainWindow code-behind
FileViewerControl (UserControl) code-behind
In this project, i am using an MVVM pattern.That isn't MVVM
sure, it isnt' and it doesnt answer my question
Avoid using code-behind and use Bindings and commands
the example project posted here is just a dummy project (and yes it isn't using MVVM) but my real project do. For sake of this question just ignore that