.netwpfadorneradornerlayeradornerdecorator

What's the point to WPF adorners?


I've recently developed a drawing component for my company, featuring a Canvas on which you can draw certain shapes using click-and-drag. For each shape, I placed two adorners on its AdornerLayer: One for increased hit detection (basically a transparent rectangle that would exceed the shape's boundaries by a few pixels), and another for resizing (four Thumb controls on the corners).

But, I ran into many problems when implementing some of the features of the component, all adorner related.

I don't quite remember which other issues I had, but this was more than enough to make me wonder about the usefulness of Adorners, and I'm seriously considering not using them in my next project, which is similar to the one I described.

So, can anyone tell me what could possibly be the pros of using these seemingly useful but incredibly annoying things?


Solution

  • I think you already know the answer to your question. They save time in some aspects, and cause problems in others. If you were to code this designer behavior using a variety of UserControls, you would find yourself writing a lot of boilerplate control classes to wrap the elements that you actually wanted to edit. If, on the other hand, you tried to write separate editing controls and intelligently overlay them, you would be writing boilerplate code to keep their positions and sizes in sync. The approach you took, using adorners, resulted in a lot of (fairly boilerplate) code to manage events.

    While adorners may not be the best tool for this particular task, they are still a useful tool for other, simpler tasks. I recently wrote a similar kind of "design surface" and adorners were a godsend for two pieces:

    1. The drag-drop behavior. When I dragged different elements, they needed to have different visual previews; this was remarkably easy to accomplish using a custom adorner and data templates.
    2. The selection rectangle or "lasso." You can see something similar when you hold your left mouse button down on a Windows desktop and drag the pointer around. It creates a semi-transparent box that can select multiple elements. I was able to create this behavior almost instantly with the adorner layer, whereas creating my own custom control resulted in a lot of unnecessary book-keeping.

    I think what you discovered in your project is that you may have been using adorners to try and accomplish too much. But don't throw the baby out with the bathwater-- they are still very useful in certain scenarios.