Sunday, September 19, 2010

Using HTML formatting when binding variables in MXML

A while ago, I was creating a component that had a repeater, whose  data provider was composed of objects with of 3 strings, and I wanted to format differently each string. This is a sample output of my repeater:



Item 1: small - $1 
Item 2: Medium - $2
Item 3: large - $3

The first string in each object is bolded, the second is italicized, and the third is colored blue.
The first attempt to obtain these results failed, and it looked like this:

<mx:Repeater id="myRepeater"
    dataProvider="{itemsAC}"
    recycleChildren="true"
    height="100%"
    width="100%">
    <mx:Text>
        <mx:htmlText>
            <![CDATA[Item <b>{myRepeater.currentItem.id}</b>: <i>{myRepeater.currentItem.size}</i> - <font color="#005D84">{myRepeater.currentItem.price}</font>]]</mx:htmlText>
    </mx:Text>
</mx:Repeater>
The code above successfully styles the text, but the binding does not work. The following output is displayed when the above code is run:


Item {item.id}: {item.size} - {item.price}
Item {item.id}: {item.size} - {item.price}
Item {item.id}: {item.size} - {item.price}
After investigating a bit further, I came up with the solution to this problem, where both the styling of the text and the data binding work:


<mx:Repeater id="myRepeater"
    dataProvider="{itemsAC}"
    recycleChildren="true"
    height="100%"
    width="100%">
    <mx:Text id="warningText"
        htmlText="Item &lt;b&gt;{myRepeater.currentItem.id} - &lt;/b&gt; {messageRepeater.currentItem.size} - &lt;font color=&quot;#005D84&quot;&gt;{messageRepeater.currentItem.price}&lt;/font&gt;"/>
</mx:Repeater>
In order to do binding, MXML should be used. However, HTML tags don't work in MXML, you have specify HTML markup by using the &lt;, &gt;, and &amp; character entities in place of the left angle bracket (<), right angle bracket (>), and ampersand (&) HTML delimiters.  For more information on this, check put the adobe livedocs: 
http://livedocs.adobe.com/flex/3/html/help.html?content=textcontrols_08.html


There are several other ways to accomplish this outcome,and this is just one of them. I hope I have saved  you some time by sharing this solution  :-)