Filtered User Selection

Filtered User Selection

PickObject(), PickObjects() and PickElementsByRectangle() all have overloads that take an ISelectionFilter as a parameter. ISelectionFilter is an interface that can be implemented to filter objects during a selection operation. It has two methods that can be overridden: AllowElement() which is used to specify if an element is allowed to be selected, and AllowReference() which is used to specify if a reference to a piece of geometry is allowed to be selected.

The following example illustrates how to use an ISelectionFilter interface to limit the user's selection to elements in the Mass category. It does not allow any references to geometry to be selected.

Code Region 7-4: Using ISelectionFilter to limit element selection

public static IList<Element> GetManyRefByRectangle(UIDocument doc)
{
        ReferenceArray ra = new ReferenceArray();
        ISelectionFilter selFilter = new MassSelectionFilter();
        IList<Element> eList = doc.Selection.PickElementsByRectangle(selFilter, 
                "Select multiple faces") as IList<Element>;
        return eList;
}

public class MassSelectionFilter : ISelectionFilter
{
        public bool AllowElement(Element element)
        {
        if (element.Category.Name == "Mass")
        {
                return true;
        }
        return false;
        }

        public bool AllowReference(Reference refer, XYZ point)
        {
                return false;
        }
}

The next example demonstrates the use of ISelectionFilter to allow only planar faces to be selected.

Code Region 7-5: Using ISelectionFilter to limit geometry selection

public void SelectPlanarFaces(Autodesk.Revit.DB.Document document)
{
        UIDocument uidoc = new UIDocument(document);
        ISelectionFilter selFilter = new PlanarFacesSelectionFilter(document);
        IList<Reference> faces = uidoc.Selection.PickObjects(ObjectType.Face, 
                selFilter, "Select multiple planar faces");
}

public class PlanarFacesSelectionFilter : ISelectionFilter
{
        Document doc = null;
        public PlanarFacesSelectionFilter(Document document)
        {
                doc = document;
        }
        
        public bool AllowElement(Element element)
        {
                return true;
        }
        
        public bool AllowReference(Reference refer, XYZ point)
        {   
                if (doc.GetElement(refer).GetGeometryObjectFromReference(refer) is PlanarFace)
                {
                        // Only return true for planar faces. Non-planar faces will not be selectable 
                        return true; 
                }
                return false;
        }
}

For more information about retrieving Elements from selected Elements, see Walkthrough: Retrieve Selected Elements in the Getting Started section.