Attempting to hide/unhide linked Revit files using Document.ActiveView.SetVisibility(), as shown the code below throws the following exception:
Here is the code which throws the above given exception:
FilteredElementCollector collector =
new FilteredElementCollector(doc);
Element linkedFile =
collector.OfCategory(BuiltInCategory.OST_RvtLinks).FirstElement();
if (linkedFile != null)
{
//read its category and set the visbility
Category category = linkedFile.Category;
doc.ActiveView.setVisibility(
category,
!category.get_Visible(doc.ActiveView));
}
How can we use the Revit API to control the visibility of Linked files, specifically hiding and un-hiding the Linked files?
To hide/unhide linked files, we can use the Document.Element.HideElements() (or the UnHideElements, as the case might be). The following self explanatory code snippet shows the usage of these two APIs.
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
namespace Revit.SDK.Samples.HelloRevit.CS
{
[Transaction(TransactionMode.Manual)]
public class Command : IExternalCommand
{
public Result Execute(ExternalCommandData commandData,
ref string message,
ElementSet elements)
{
UIApplication uiApp = commandData.Application;
Document doc = uiApp.ActiveUIDocument.Document;
//find the linked files
FilteredElementCollector collector = new FilteredElementCollector(doc);
ICollection<ElementId> elementIdSet =
collector
.OfCategory(BuiltInCategory.OST_RvtLinks)
.OfClass(typeof(RevitLinkInstance))
.ToElementIds();
using (Transaction trans =
new Transaction(doc, "LinkedFileVisibility"))
{
trans.Start();
foreach (ElementId linkedFileId in elementIdSet)
{
if (linkedFileId != null)
{
if (true ==
doc.GetElement(linkedFileId).IsHidden(doc.ActiveView))
{
if (true ==
doc.GetElement(linkedFileId).CanBeHidden(doc.ActiveView))
{
doc.ActiveView.UnhideElements(elementIdSet);
}
}
else
{
doc.ActiveView.HideElements(elementIdSet);
}
}
}
trans.Commit();
}
return Result.Succeeded;
}
}
}