Is dynamically attaching/detaching WPF behaviors a valid approach to my problem?

139 Views Asked by At

Short Version:

Is dynamically attaching/detaching WPF behaviors to/from a control at runtime a feasible practice in WPF or should I be looking for something different to solve my problem?

Long version: I have a WPF control which represents a drawing surface. The user can use any one of a number of mouse "tools". One tool draws a line, one draws a polyline, one merely selects exiting items, etc. etc.

I handle this in code-behind for mouse events. Unfortunately no matter how much I try to generalize it, there is a lot of switching on tool type because the tools do very different things. Consequently, it is difficult to maintain. Adding new tools requires too many edits and testing. The handlers keep on growing larger.

I need to make this control relatively easy for the next developer on this project to understand it and to add a new tool without worrying about breaking anything.

It would seem that WPF behaviors would provide a natural way to simplify this and make it more modular; You set a particular "tool behavior" on the control and it handles the only mouse events it needs, altering the control properties as necessary. Different tool code is no longer mixed together.

But this approach differs from the way I've used WPF behaviors in the past. It would require me be able to dynamically attach/detach behaviors at run time with the push of a button. That is new to me. Usually I just have a simple behavior that I declare on a control once in XAML and it stays that way for the lifetime of the control. In fact, all of the WPF Behavior examples I've ever seen have been the sort where you set up the behavior one time in XAML and forget about it.

So I'm wondering has anyone out there done something like this? Is this an approach I should pursue or would it probably end up proving unwieldy? Or should I be looking for a different solution?

0

There are 0 best solutions below