Zed-K
Zed-K

Reputation: 999

Flex - Binding on width property using percentages in MXML code

Is it possible to set a percentage value for the width property of an UIComponent defined in MXML using data binding?

What I try to achieve is something like this (which doesn't work):

<s:Button width="{buttonWidth}%"/>


I know that using percentage for width or height properties in MXML is kind of a hack in the Flex SDK, since they're supposed to accept numerical values only, but since percentWidth and percentHeight aren't available in MXML, I'm pretty stuck =/

I would really like to avoid using code to do such a simple thing, in order to keep my code as clear and readable as posible.

Anybody got a clue about how to achieve this?

Upvotes: 2

Views: 2133

Answers (4)

Victor Sheyanov
Victor Sheyanov

Reputation: 91

Elegant solution would be:

<s:Button percentWidth="{buttonWidth}" />

Upvotes: 1

Antoine
Antoine

Reputation: 1268

I used the same value on several items, and didn't want to add a fx:binding on each one, so I did something like this :

    <fx:Script>
    <![CDATA[
        private var buttonWidth:int=50;
        private function updateWidth(event:Event):void {
            event.currentTarget.percentWidth=buttonWidth;
        }
    ]]>
</fx:Script>
<s:Button id="button1" add="updateWidth(event)"/>
<s:Button id="button2" add="updateWidth(event)"/>
<s:Button id="button3" add="updateWidth(event)"/>
<s:Button id="button4" add="updateWidth(event)"/>
<s:Button id="button5" add="updateWidth(event)"/>

Upvotes: 2

jvignali
jvignali

Reputation: 76

K, I ran into that same issue: binding a percentage value to the percentWidth property of a spark container. First, I kinda fixed it with some code but didn't like it, then I found out that I could declare the binding in a nice MXML way:

<fx:Script>
  <![CDATA[
    [Bindable] private var pWidth:uint;
  ]]>
</fx:Script>

<fx:Binding source="pWidth" destination="myContainer.percentWidth"/>

<s:Group id="myContainer" />

Works like a charm :)

Upvotes: 3

Robusto
Robusto

Reputation: 31913

You could extend the Button class (maybe call it a PercentButton, whatever) and give it a bindable property (call it _pctWidth, say), give it a public getter and a public setter, and in your setter you do this:

[Bindable]
private var _pctWidth:Number;

public function set pctWidth(value:Number) : void {
  _pctWidth = value;
  percentWidth = _pctWidth;
  invalidateDisplayList();
}

Upvotes: 0

Related Questions