献上一个可以绑定样式的工具类StyleBindingUtils

开门见代码:
package com.montage.binding.utils
{
	import mx.binding.utils.ChangeWatcher;
	import mx.styles.IStyleClient;
	
	/**
	 * Flex的绑定功能为我们的日常提供很多的方便
	 * 但是Flex只提供了属性的绑定类->BindingUtils;
	 * 如果要实现绑定控件的Style还要自己用ChangeWatcher去侦听事件
	 * 有了StyleBindingUtils这一切将变的简单
	 * StyleBindingUtils封装了ChangeWatcher进行了Style的绑定实现,
	 * 为您的开发提供了更多方便和快捷
	 * @author montage
	 */	
	public class StyleBindingUtils
	{
		public function StyleBindingUtils()
		{
		}
		
		public static function bindStyle(
										site:IStyleClient, prop:String,
										host:Object, chain:Object,
										commitOnly:Boolean = false):ChangeWatcher
		{
			var w:ChangeWatcher = 
				ChangeWatcher.watch(host, chain, null, commitOnly);
			
			if(w != null )
			{
				var assign:Function = function(event:*):void
				{
					site.setStyle(prop, w.getValue());
				}
				w.setHandler( assign );
				assign(null);
			}
			
			return w;
		}
										
		
	}
}


测试文件:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" creationComplete="init()">
	<mx:Script>
		<![CDATA[
			import mx.graphics.Stroke;
			import mx.graphics.IStroke;
			import com.montage.binding.utils.StyleBindingUtils;
			
			/**
			 * 定义一个Stroke, 默认颜色为0x333333
			 */
			private var borderStroke:Stroke = new Stroke(0x333333, 0, 1);
			
			private function init():void
			{
				/**
				 * 进行绑定:把container的borderColor样式属性绑定到borderStroke的color属性上
				 */
				StyleBindingUtils.bindStyle(container, "borderColor", borderStroke, "color");
			}
			
			private function changeHandler():void
			{
				/**
				 * 设置borderStroke的color属性
				 * 被绑定对象会联运变化
				 */
				borderStroke.color = borderColor.selectedColor;
			}
			
		]]>
	</mx:Script>
	<mx:Canvas width="200" height="200" id="container" borderThickness="2" borderStyle="solid"/>
	<mx:ApplicationControlBar>
		<mx:FormItem label="borderColor:">
			<mx:ColorPicker id="borderColor" change="changeHandler()"/>
		</mx:FormItem>
	</mx:ApplicationControlBar>
</mx:Application>

你可能感兴趣的:(xml,Flex)