Selecting an item in a Flex tree and opening that parent branch
I found a little gotcha when selecting an item in a Flex tree. Sometimes you may want to auto-select one of the items in a tree when it is first loaded; it may also make sense to make sure that the parent branch of the item is open so that the highlighted item is visible to the user. In fact, if the branch is not open, I was seeing an error thrown by the Flex framework. So I tried a little bit of code that looked something like this:
tree.openItems = target.parent; tree.selectedItem = target;
All nice and easy, right? Well, when I ran the application I found that the selection was not working; the tree would be opened at the right branch, but the selected item was not being set. The fix is to make sure that we call validateNow() after we set the openItems property:
tree.openItems = target.parent; tree.validateNow(); tree.selectedItem = target;
Voila! Work perfectly. Why does it work? If you have time, digging around in the source code for the validateNow() function will no doubt make it clear.


