Skip to main content

Retain Scroll Position when changing the dataprovider of a spark flex4.5 datagrid

How The Code Works
The code is pretty simple. You instantiate a class level variable to hold the current location of the scroll bar. propertyChangeHandler() updates that variable and when the dataprovider is changed the grid is scrolled down to the last value of the variable i.e the last location of the scroll bar.
<fx:Script>

<![CDATA[
private var scrollerPosition:Number=0;
private var _gridDP:XMLListCollection;

public
[Bindable]
function get GridDataProvider():XMLListCollection{
return this._gridDP;
}

public function set GridDataProvider(value:XMLListCollection):void{
this._gridDP = value;
}
public function group1_creationCompleteHandler(event:FlexEvent):void
{
_gridDP.addEventListener(CollectionEvent.COLLECTION_CHANGE,setGridScrollPosition);
gridMain.grid.layout.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE,propertyChangeHandler);
}

private function propertyChangeHandler(e:PropertyChangeEvent):void {
if (e.property == "verticalScrollPosition" || e.property == "horizontalScrollPosition")
{
trace("scroll position changed");
var curScrollPosition:Number = e.newValue as Number;
if(curScrollPosition !=0)
this.scrollerPosition = curScrollPosition;
}
}

private function setGridScrollPosition(event:Event):void{
gridMain.validateNow();
gridMain.grid.verticalScrollPosition = this.scrollerPosition;
}
]]>

</fx:Script>

<s:DataGrid id="gridMain" dataProvider="{GridDataProvider}" width="100%" height="100%" fontSize="18" >

Comments