1

考虑以下单选按钮示例。

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
<mx:Script>
<![CDATA[
    private function getRb1():RadioButton {
        trace(rb1 == null);
        return rb1;                     
    }   
]]>
 </mx:Script>
<mx:VBox>
    <mx:RadioButtonGroup **id="rbg" selection="{getRb1()}**"/>      
    <mx:RadioButton id="rb1" label="Radio Button 1" />
    <mx:RadioButton id="rb2" label="Radio Button 2" />
    <mx:RadioButton id="rb3" label="Radio Button 3" />
</mx:VBox>  
 </mx:Application>

问题是我在定义 RadioButtonGroup 时不能引用 rb1,当时 rb1 为空,但我可以使用 selectedValue 来设置初始选择。

我只是想知道这是一些特殊情况还是在一般情况下引用 mxml 中的组件是不安全的。

谢谢,

4

2 回答 2

1

我不太确定你在问什么,但希望这能回答你的问题——来自 Flex 文档:

RadioButtonGroup.selection
包含对组中当前选定的 RadioButton 控件的引用。您只能在 ActionScript 中访问该属性;它在 MXML 中不可设置。将此属性设置为 null 会取消选择当前选定的 RadioButton 控件。

不过,总的来说,在 MXML 中进行组件引用是完全可以的。这就是通常处理效果的方式,以及许多其他事情。例如:

<mx:Glow id="g" />
<mx:Label showEffect="{g}" />

但是,在您的情况下,假设您在设置所选项目时遇到问题,可能是因为您没有group在单选按钮上指定属性;省略将组组件与各个按钮分离。添加后,您可以使用Bindable包含对组件的引用的变量来绑定组的选择属性,如下所示:

<mx:Script>
    <![CDATA[

        [Bindable]
        private var selectedRadioButton:RadioButton;    

        private function this_creationComplete(event:Event):void
        {
            selectedRadioButton = rb1;
        }

        private function btn_click(event:Event):void
        {
            selectedRadioButton = rb2;
        }

    ]]>
 </mx:Script>
<mx:VBox>
    <mx:RadioButtonGroup id="rbg" selection="{selectedRadioButton}" />
    <mx:RadioButton id="rb1" group="{rbg}" label="Radio Button 1" />
    <mx:RadioButton id="rb2" group="{rbg}" label="Radio Button 2" />
    <mx:RadioButton id="rb3" group="{rbg}" label="Radio Button 3" />

    <mx:Button label="Choose a Different Button" click="btn_click(event)" />
</mx:VBox> 

这有意义吗?希望它不是完全偏离标准。回帖让我知道,我会尽我所能提供帮助。

于 2009-01-30T21:02:05.090 回答
0

通常:仅仅因为在 MXML 中声明了控件并不意味着它在运行时可用(它可能从 AS 中删除,尚未创建,未添加到阶段,因此某些属性尚不可用)。这表明在运行时访问组件并依赖于值是不安全的。

于 2009-01-31T01:20:10.420 回答