StyleBindingUtils可以绑定样式的工具类

Flex自带的有一个BindingUtils类,可以把两个类的属性绑定起来,但是不能绑定样式(Style),样式是Flex中常用的特性,看其BindingUtils源码,绑定技术本身是依靠于ChangeWatcher,所以照着BindingUtils写一个可以绑定样式的方法。
StyleBindingUtils:

package org.beasy.binding.utils
{
	import mx.binding.utils.ChangeWatcher;
	import mx.styles.IStyleClient;
 
	/**
	 * Flex的绑定功能为我们的日常提供很多的方便
	 * 但是Flex只提供了属性的绑定类->BindingUtils;
	 * 如果要实现绑定控件的Style还要自己用ChangeWatcher去侦听事件
	 * 有了StyleBindingUtils这一切将变的简单
	 * StyleBindingUtils封装了ChangeWatcher进行了Style的绑定实现,
	 * 为您的开发提供了更多方便和快捷
	 * @author Marco
	 */
	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"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" 
			   xmlns:s="library://ns.adobe.com/flex/spark" 
			   xmlns:charts="org.beasy.charts.*"
			   xmlns:mx="library://ns.adobe.com/flex/halo" minWidth="1024" minHeight="768" fontSize="12">
	<fx:Script>
		<![CDATA[
			import mx.graphics.SolidColorStroke;
 
			import org.beasy.binding.utils.StyleBindingUtils;
 
			/**
			 * 定义一个Stroke, 默认颜色为0x333333
			 */
			private var background:SolidColorStroke = new SolidColorStroke(0x333333, 0, 1);
 
			private function init():void
			{
				/**
				 * 进行绑定:把container的borderColor样式属性绑定到borderStroke的color属性上
				 */
				StyleBindingUtils.bindStyle(container, "backgroundColor", background, "color");
			}
 
			private function changeHandler():void
			{
				/**
				 * 设置borderStroke的color属性
				 * 被绑定对象会联运变化
				 */
				background.color = backgroundColor.selectedColor;
			}
		]]>
	</fx:Script>
	<mx:Canvas width="200" height="200" id="container" borderThickness="2" borderStyle="solid"/>
	<mx:ControlBar width="100%">
		<mx:FormItem label="背景色:">
			<mx:ColorPicker id="backgroundColor" change="changeHandler()"/>
		</mx:FormItem>
	</mx:ControlBar>
</s:Application>

相关日志

  1. 纬度网 说道:

    StyleBindingUtils可以绑定样式的工具类…

    Flex自带的有一个BindingUtils类,可以把两个类的属性绑定起来,但是不能绑定样式(Style),样式是Flex中常用的特性,看其BindingUtils源码,绑定技术本身是依靠于ChangeWatcher,所以照着BindingUtils写一个可以绑定样式的方法。 StyleBindingUtils: package org.beasy.binding.utils { import mx.binding.utils.ChangeWatcher; import mx.styles.ISty…

添加评论