Wednesday, April 1, 2009

Behaviors and Uses of Collapsed vs. Zero Opacity

While visually, setting a XAML element's opacity to zero is the same as setting visibility to collapsed, the two have different behaviors when it comes to detecting interaction with the mouse. An element whose visibility is set to 'collapsed' is undetectable by a mouse; it is as if the element has been removed from the visual tree. Setting an element's opacity to zero, however, makes it invisible while it is still detectable by the mouse, e.g. a button with zero opacity is still clickable.

This distinction is useful in a number of ways. One application is creating an invisible button on a page that the knowledgeable user can click to trigger a desired action such as debugging or a special report. To do this, you would create a button with opacity equal to zero. Conversely, you may have a button you wish to deactivate as well as hide, in which case you would set visibility to collapsed.

Another application of zero opacity is to create a shield which allows lower level elements to display but renders them inactive - for example, you may want to do this during an asynchronous operation like retrieving an RSS feed, during which you want to prevent user interaction. In this case, you could create a large rectangle covering the page but set its opacity to zero -- this would allow the user to see what is happening underneath but prevents them from doing anything. When the asynchronous event is complete, the rectangle could then be collapsed to allow user interaction.

Opacity and visibility are also be different in their use for visualization, especially during animations. Opacity is a continuous value that ranges from 0 to 100% in Blend or 0 to 1 in XAML, making it a good candidate for animations, where an element can move from one value to another during a given timeframe. Visibility is an on/off value, either visible or collapsed, and changes at one point in time. These differences in visualization, combined with differences in mouse interaction, should be considered by the designer/developer when choosing between the two properties.

The most important thing to remember is just because you can't see it, doesn't mean you can't click it! An element whose opacity = 0 can still be an active control on your Silverlight application. If you want something to be really 'gone', set its visiblity to collapsed.

No comments: