Flex中通过扩展Label对DataGrid进行格式化显示的例子
By Minidxer | July 29, 2008
接下来的例子演示了Flex中如何通过扩展Label,对DataGrid进行格式化显示。例子中如果金额大小小于0,则红色显示,否则为黑色。注意标签是自定义的Label。
让我们先来看一下Demo(可以右键View Source或点击这里察看源代码):
下面是完整实现代码(或点击这里察看):
Download: main.mxml
- <?xml version="1.0" encoding="utf-8"?>
- <!-- http://blog.flexexamples.com/2007/08/20/formatting-a-flex-datagrid-control-using-a-custom-item-renderer/ -->
- <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
- layout="vertical"
- verticalAlign="middle"
- backgroundColor="white">
- <mx:Script>
- <![CDATA[
- import mx.controls.dataGridClasses.DataGridColumn;
- import mx.utils.ObjectUtil;
- private function price_labelFunc(item:Object, column:DataGridColumn):String {
- return currencyFormatter.format(item.@price);
- }
- private function price_sortCompareFunc(itemA:Object, itemB:Object):int {
- return ObjectUtil.numericCompare(itemA.@price, itemB.@price);
- }
- ]]>
- </mx:Script>
- <mx:XML id="itemsXML">
- <items>
- <item name="Item 1" price="1.32" />
- <item name="Item 2" price="-12.23" />
- <item name="Item 3" price="4.96" />
- <item name="Item 4" price="-0.94" />
- </items>
- </mx:XML>
- <mx:Style>
- .centered {
- text-align: center;
- }
- </mx:Style>
- <mx:CurrencyFormatter id="currencyFormatter"
- precision="2"
- useNegativeSign="false" />
- <mx:DataGrid id="dataGrid" dataProvider="{itemsXML.item}">
- <mx:columns>
- <mx:DataGridColumn dataField="@name"
- headerText="Name:"
- headerStyleName="centered" />
- <mx:DataGridColumn dataField="@price"
- headerText="Price:"
- textAlign="right"
- headerStyleName="centered"
- labelFunction="price_labelFunc"
- sortCompareFunction="price_sortCompareFunc"
- itemRenderer="PriceLabel" />
- </mx:columns>
- </mx:DataGrid>
- </mx:Application>
下面是自定义的Label扩展部分代码:
Download: PriceLabel.as
- package {
- import mx.controls.Label;
- import mx.controls.listClasses.*;
- public class PriceLabel extends Label {
- private const POSITIVE_COLOR:uint = 0x000000; // Black
- private const NEGATIVE_COLOR:uint = 0xFF0000; // Red
- override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
- super.updateDisplayList(unscaledWidth, unscaledHeight);
- /* Set the font color based on the item price. */
- setStyle("color", (data.@price <= 0) ? NEGATIVE_COLOR : POSITIVE_COLOR);
- }
- }
- }
代码:Peter deHaan 翻译/整理/编译:minidxer
Topics:
Flex |
Tags: CurrencyFormatter, DataGrid, itemRenderer, sortCompareFunction