过去在对DataGrid设置行背景色时,感觉还是挺方便的,只要重写DataGrid的,如下
如果你还是不是很明白可以参考我以前的博客http://blog.csdn.net/terryzero/archive/2009/10/12/4657277.aspx
今天我碰到个需求是要对List行变色,由于我想DataGrid和List都是继承与ListBase,都有 override protected function drawRowBackground(s:Sprite, rowIndex:int, y:Number, height:Number, color:uint, dataIndex:int):void
这个方法,所以我就想当然,照葫芦画瓢,也重写了这个方法,但经过调试怎么也调用不到这个方法。搞的我非常费解,难道这个方法没用的啊?网上查了好久,国内没啥这方面的好文章,突然一篇国外的文章启发了我。如下
All the listy components in Flex (List, Datagrid, Tree, etc.) have a protected method called drawRowBackground which is in charge of drawing the background for a given row. You typically use it to color a given row based on some facet of the data the row represents (e.g. red background for rows with a negative bank balance).
With DataGrid, it's easy to use, just subclass DataGrid and override the method, parameterized so you can pass in a function to compute the color for each row based on the row index/data/original color/etc. With List (and since ComboBox uses a List, ComboBox too), it's a bit nastier.
For some reason, List will only call drawRowBackground if the 'alternatingItemColors' style is set for the List. So if you want to color your List rows, you have to supply that style, which you'll likely immediately be overriding.
原来List也有alternatingItemColors属性,设了以后问题果然解决了,如下
<wn:MOBColorList id="nodeList" width="50%" height="100%" dropEnabled="true" dataProvider="{nodes}"
dragOver="doDragOver(event)" dragEnter="doDragEnter(event)" keyDown="deleteField(event)"
alternatingItemColors="[0xEEEEEE, 0xDFDFDF]"
dragDrop="doDragDrop(event)" iconFunction="{IconUtil.setHierarchyTreeNodeIcons}"
rowColorFunction="setCustomColor"/>
其实我根本不希望行交替变色,所以就把alternatingItemColors="[0xFFFFFF, 0xFFFFFF]",哈哈搞定了,但还不是很清楚为什么一定要设。研究了下List的源码,使我茅舍顿开,如下
原来不设定alternatingItemColors根本不会调用drawRowBackgrounds方法,而DataGrid这种控件alternatingItemColors有默认值,所以一定会调用。不要把flex看的很绚丽很简单,其实还是有很多值得研究的地方,flex本身也不是很成熟,深入源码还有很多不尽人意的地方。