سؤال

I have a list and setting the list to the exact item that is in it's dataProvider would not select it programmatically. Here is the code:

            if (list.selectedItem != iDocument) {

                var length:int = documentsCollection.length;
                for (var i:int;i<length;i++) {
                    jDocument = IDocumentData(documentsCollection.getItemAt(i));


                    if (jDocument.uid==iDocument.uid) {
                        list.selectedItem = IDocumentData(documentsCollection.getItemAt(i));
                        break;
                    }
                }
            }
هل كانت مفيدة؟

المحلول

There were two issues.

I had applied a sort to the ArrayCollection and the field was not in the item. I had copied code from another project and the field was "@name" since it was an XMLListCollection. The sort field should have been set to "name".

So when you set the selectedItem property it looks in the collection and if the collection has a sort then it looks in the findItem() call which does a compare function that checks if the item has the field name in the item. If not it throws an error. Since I had the incorrect field name an error was thrown. If an error is thrown then the pursuit to find the selected item is abandoned and selected index is -1.

Code from ListCollectionView.as:

    try
    {
        return sort.findItem(localIndex, values, mode, insertIndex);
    }
    catch (e:SortError)
    {
        // usually because the find critieria is not compatible with the sort.
    }

    return -1;

Code from Sort.as:

    var hasFieldName:Boolean;
    try
    {
        hasFieldName = values[fieldName] !== undefined;
    }
    catch(e:Error)
    {
        hasFieldName = false;
    }
    if (hasFieldName)
    {
        if (!hadPreviousFieldName)
        {
            message = resourceManager.getString(
                "collections", "findCondition", [ fieldName ]);
            throw new SortError(message);
        }
        else
        {
            fieldsForCompare.push(fieldName);
        }
    }

The second issue was that the List uses an exact equality operator so it uses "===" instead of "==". This means that you have to make sure you are passing in the exact instance of the item in the list.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top