views:

195

answers:

1

I am using Flex to create a small form. All I have at the moment is a List component, that I want to populate with a list of font names.

I am getting the fonts using Font.enumerateFonts(true);. This returns an array of flash.text.Font objects.

The Font objects have a fontName property that is a String of that fonts name.

My problem is that I can't figure out how to bind the List's dataProvider to the fontName property of each of the Font objects in the Array.

Is there a way to do this just with binding? and not creating a new array of Strings by looping through the Font objects?

+3  A: 

You're probably looking for the labelField property of the List control. Here's a working example:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" initialize="onInitialize()">

    <mx:Script>
     <![CDATA[

      import mx.collections.ArrayCollection;

      [Bindable]
      private var fonts:ArrayCollection;

      private function onInitialize():void
      {
       fonts = new ArrayCollection(Font.enumerateFonts(true));
      }

     ]]>
    </mx:Script>

    <mx:List dataProvider="{fonts}" labelField="fontName" />

</mx:Application>

Also note that I'm using an ArrayCollection for the binding (as opposed to an Array), since Arrays don't support binding in the way you're expecting.

Hope that helps! Any questions, feel free to post back.

Christian Nunciato
That works great! I was trying to do it all within the dataProvider binding, but I *was* using an ArrayCollection. Would you mind explaining a bit more of HOW it's working please? like, how does it know to look inside each Font object for the fontName property?
TandemAdam
Glad it helped! The docs (in this case, mx.controls.listClasses.ListBase, from which List derives) could probably do it best: the labelField property specifies "the name of the field in the data provider [e.g., flash.text.Font] items to display as the label. By default the List looks for a property named 'label' on each item and displays it. However, if the data objects do not contain a label property, you can set the labelField property to use a different property in the data object. An example would be 'FullName' [or 'fontName'] when viewing a set of people names fetched from a database."
Christian Nunciato
That is perfect! Thanks for your help. I have gladly up voted your answer and comment. I should really check the docs :)
TandemAdam