views:

227

answers:

1

I have a class that needs to notify that something significant has occured. The class is in a WPF-project, even though this specific class, is lookless (and doesn't inherit from UIElement, neither directly or indirectly).

Normally, I just register a RoutedEvent to get this functionality but as this class neither has AddHandler nor RemoveHandler, I can't get it to work. Anyone knows of another way of get the RoutedEvent behaviour?

A: 

As far as i know, if your class isn't a UIElement, it cannot be part of the visual tree, and if it isn't part of the visual tree, you cannot throw RoutedEvents. They're strictly a UI concept.

I think the recommended approach would be to either make your class inherit from UIElement, or if that's not possible/desired, create a counterpart for your class which does inherit from UIElement and use this second class in the visual tree where you would normally place your original class.

Bubblewrap
Why not just use regular .net events? Define the event in your lookless class, fire the event in your lookless class when something happens, and any other classes that want to be notified can simply sign up for this event. You can even make this event static if that works for your particular application.
Adel Hazzah
That depends on the specific situation, but the poster asked for RoutedEvents, i assume there's a reason for that. Perhaps a regular event will do in his case...i wouldn't know, don't have enough details for that. But both have their advantages. RoutedEvents are particularly useful if the listener doesn't have a direct reference to the source of the event. For example you have a container control which must react to a specific event, but the container will not always know exactly which controls inside it can/will throw it. The controls can be several levels deep, or created by a template.
Bubblewrap
Regular events it is! I was merely after a way of notifying other classes and don't necessarily need the extra functionality of a RoutedEvent. I haven't coded a lot of C# before WPF so I wasn't quite sure what existed before RoutedEvents. So, thanks Adel and Bubblewrap!
Andreas