Macromedia flex 2 手册
192
Creating Custom Style Properties
Setting default style values
One of the issues that you have to decide when you create a style property for your
component is how to set its default value. Setting a default value for a style property is not as
simple as calling the
component is how to set its default value. Setting a default value for a style property is not as
simple as calling the
setStyle
()
method in the component’s constructor; you must take into
consideration how Flex processes styles, and the order of precedence of styles.
When Flex compiles your application, Flex first examines any style definitions in the
<mx:Style>
tag, before it creates any components. Therefore, if you call
setStyle()
from
within the component’s constructor, which occurs after processing the
<mx:Style>
tag, you
set the style property on each instance of the component; this overrides any conflicting CSS
declarations in the
declarations in the
<mx:Style>
tag.
The easiest way to set a default value for a style property is to define a static initializer in your
component. A static initializer is executed once, the first time Flex creates an instance of a
component. In
component. A static initializer is executed once, the first time Flex creates an instance of a
component. In
, you defined a static initializer, by
using the
classConstructed
variable and the
classConstruct()
method, as part of the
StyledRectangle.as class.
The
classConstruct()
method is invoked the first time Flex creates a StyledRectangle
component. This method determines a style definition for the StyledRectangle class already
exists, defined by using the
exists, defined by using the
<mx:Style>
tag. If no style is defined, the
classConstruct()
method creates one, and sets the default value for the style property.
Therefore, if you omit the
<mx:Style>
tag from your application, the style definition is
created by the
classConstruct()
method, as the following example shows:
<?xml version="1.0"?>
<!-- skinstyle\MainRectNoStyles.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:MyComp="myComponents.*">
<MyComp:StyledRectangle/>
</mx:Application>
<!-- skinstyle\MainRectNoStyles.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
xmlns:MyComp="myComponents.*">
<MyComp:StyledRectangle/>
</mx:Application>