Hit Testing

One issue that is somewhat germane to control styling is the issue of transparency and hit testing. Generally WPF just does the right thing for you. If, for example, you created a template for a Button that contained only an ellipse, the Button would only respond to a mouse click on the ellipse itself and not on the "corners" around the ellipse.

This works because the Button only gets mouse events on pixels where it has drawn something. This is usually what you want and what you would expect. There is a snag though.

The snag is characterized by the experience of a commenter on this site who was trying to get hit testing on a Canvas. He found that he couldn't get a mouse event to fire unless he set a background on the Canvas. In the context of the model I just described, this makes sense but can be frustrating.

We also hit similiar issues in control styles where we want hit testing on a region of the control that appears transparent. This might be the case in MenuItem or a ListBoxItem, where the item spans the width of some container but only has visible content in a portion of it.

The work around is the magic system brush called Transparent. This actually maps to the color "#00000000" and the two can be used interchangably. In fact, the only important thing here is that the value is non-null and the alpha value (the first two digits in the hex representation) is zero. By making it non-null, we enable hit testing. By making the alpha zero, we prevent it from actually drawing anything.

You can see this work in a simple example by creating two buttons and setting the background of one to null and the other to Transparent. They will look the same but behave differently.



Loading... Show