按钮控制DataGrid的Column升序或降序(固定排序)

突然应对一个问题,DataGrid的dataProvider数据是可变的,但DataGrid的排序方式是轮循的,因此有些时候需要总是升序或降序,所以加上一个参数always,并在方法中进行改进,代码如下:
<?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:mx="library://ns.adobe.com/flex/mx" 
			   minWidth="955" minHeight="600">
	<s:layout>
		<s:VerticalLayout />
	</s:layout>
	<fx:Script>
		<![CDATA[
			import mx.collections.ArrayCollection;
			import mx.collections.Sort;
			import mx.collections.SortField;
			import mx.events.DataGridEvent;

			private const _arr:Array = [	
				{"str": "B", "num": 34},
				{"str": "A", "num": 256},
				{"str": "D", "num": 97},
				{"str": "C", "num": 18},
				{"str": "E", "num": 0}
			];

			private function onClick(columnIndex:int = -1,
					sortDescending:Boolean = true, always:Boolean = true):void{
				var _column:DataGridColumn = grid.columns[columnIndex];
				_column.sortDescending = sortDescending;
				//==========
				if(always){
					var _sort:Sort = 
						(grid.dataProvider as ArrayCollection || {}).sort;
					if(_sort){
						var _fields:Array = _sort.fields;
						if(_fields){
							(_fields[0] as SortField).descending = 
								!sortDescending;
						}
					}
				}
				//==========
				grid.dispatchEvent(new DataGridEvent(
					DataGridEvent.HEADER_RELEASE, false, false, columnIndex));
			}

//			private function onClick(columnIndex:int = -1, 
//									 sortDescending:Boolean = true):void{
//				var _column:DataGridColumn = grid.columns[columnIndex];
//				_column.sortDescending = sortDescending;
//				grid.dispatchEvent(new DataGridEvent(
//					DataGridEvent.HEADER_RELEASE, false, false, columnIndex));
//			}
		]]>
	</fx:Script>
	<mx:DataGrid id="grid" dataProvider="{_arr}" width="320" height="240">
		<mx:columns>
			<mx:DataGridColumn dataField="str" headerText="String" />
			<mx:DataGridColumn dataField="num" headerText="Number" />
		</mx:columns>
	</mx:DataGrid>
	<s:Button label="String排序" width="100" click="onClick(0, false)" />
	<s:Button label="Number排序" width="100" click="onClick(1)" />
</s:Application>

视图:
按钮控制DataGrid的Column升序或降序(固定排序)

你可能感兴趣的:(C++,c,xml,C#)