I have a DataGrid component that I would like to update every 5 seconds. As rows are being added to this DataGrid I noticed that every update causes it to reset the scroll bar position开发者_运维问答 to the top. How can I manage to keep the scroll bar at its previous position?
make a variable to store your last scroll position and use that.
roughly something like:
var lastScroll:Number = 0;
private function creationCompleteHandler(event:FlexEvent):void{
stage.addEventListener(MouseEvent.MOUSE_UP, updateLastScroll);
}
private function updateLastScroll(event:MouseEvent):void{
lastScroll = myDataGrid.verticalScrollPosition
}
private function dataGridHandler(event:Event):void{
myDataGrid.verticalScrollPosition = lastScroll;
}
It's not the best code, but it illustrates the point, whenever someone finishes the scroll event, you store last position in a variable and you use that to restore the scroll position right after you've added new data.
I wrote a little extension class to DataGrid
based on this article. It seems to work great.
public final class DataGridEx extends DataGrid
{
public var maintainScrollAfterDataBind:Boolean = true;
public function DataGridEx()
{
super();
}
override public function set dataProvider(value:Object):void {
var lastVerticalScrollPosition:int = this.verticalScrollPosition;
var lastHorizontalScrollPosition:int = this.horizontalScrollPosition;
super.dataProvider = value;
if(maintainScrollAfterDataBind) {
this.verticalScrollPosition = lastVerticalScrollPosition;
this.horizontalScrollPosition = lastHorizontalScrollPosition;
}
}
I haven't tested this code, but it should work:
var r:IListItemRenderer;
var len:Number = dataGrid.dataProvider.length;
var i:Number;
//indexToItemRenderer returns null for items that are not visible
for(i = 0; i < len; i++)
{
r = dataGrid.indexToItemRenderer(i);
if(r)
break;
}
//now i contains the first visible item - store this in a variable
lastPos = i;
//update the dataprovider here.
//now scroll to the position
dataGrid.scrollToIndex(lastPos);
These might help:
Maintain Scroll Position after Asynchronous Postback
Maintaining Scroll Position on Postback (Scroll further down to read this)
精彩评论