Sunday, June 19, 2011

Data Binding, Displaying Images in Flex

Today we will learn a little about data binding and displaying images in our Flex application.

It is often needed to create dynamic text controls in applications. They are basically text fields that dont just contain pre-set text values, but rather data from other sources. For example, the application could first ask the user for their name, and when the user enters their name, for example, "John", a greeting message is displayed: "Hello, John!".

This is called data binding. In MXML, when we want to use this method to change a text value, we just pass the data source in { } brackets, for example, if we want a text field to display value of another text field, we would set its text property to "{otherText.text}".

To understand this better, let's create a simple application like that example with the greeting message above.

We will create a TextInput object, where the user enters the name, and a Label object, where the greeting is displayed. The greeting is a composition of "Hello, " text, the user's name, and an "!" mark in the end. Overall, the whole code will look like this:

<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx=""
<s:VGroup x="10" y="10">
<s:TextInput id="myInput" text="Your name here" />
<s:Label text="Hello, {myInput.text}!" />


And here are the results, try changing the value in the input field right now:

You can see that the value of the Label changes instantly. This makes it a powerful tool for the developer.

Data binding can be also used with other types of data. You could, for example, data bind a value in an xml file which is located on a server to a text field in your Flex application, and if the data in that xml file is updated - the text field is also updated instantly.

Now, for the second part of this tutorial - displaying images in Flex.

To display JPG, GIF, PNG and SWF files in Flex, we can use the Image component in the mx namespace. We can set a path to the image for it using the 'source' property. We can also tell Flex whether we want or dont want to scale the content of the image, using the 'scaleContent' property, which is a boolean. It is pretty straight-forward.

<mx:Image source="images/myimage.jpg" scaleContent="true" />

If you store your image in the 'lib' folder of the project, then set the path like this:

<mx:Image source="../lib/myimage.jpg" scaleContent="true" />

This works well, but it will only work as long the image can be located there - in that directory that you've specified in the path. To actually include the image in the final swf, we need to embed it. We can do it by putting the path into quotes and into ( ) brackets and including @Embed in front of it. In the end, this is what the path will look like:

<mx:Image source="@Embed('../lib/myimage.jpg')" scaleContent="true" />

That is all for today.

Thanks for reading!

No comments:

Post a Comment