IndependentTag - Как я могу назвать это в Revit?

У меня есть рабочая вкладка ленты с панелями и кнопками, которые работают при вызове диалоговых окон только для тестирования. Сейчас я пытаюсь вызвать этот фрагмент кода с сайта Autodesk, который должен создать новый тег IndependentTag, однако он не работает.

[Transaction(TransactionMode.Manual)]
public class Tagtest : IExternalCommand
{
    #region Methods

    /// <summary>
    ///       The CreateIndependentTag
    /// </summary>
    /// <param name="document">The <see cref="Document" /></param>
    /// <param name="wall">The <see cref="Wall" /></param>
    /// <returns>The <see cref="IndependentTag" /></returns>
    public IndependentTag CreateIndependentTag(Document document, Wall wall)
    {
        TaskDialog.Show("Create Independent Tag Method", "Start Of Method Dialog");
        // make sure active view is not a 3D view
        var view = document.ActiveView;

        // define tag mode and tag orientation for new tag
        var tagMode = TagMode.TM_ADDBY_CATEGORY;
        var tagorn = TagOrientation.Horizontal;

        // Add the tag to the middle of the wall
        var wallLoc = wall.Location as LocationCurve;
        var wallStart = wallLoc.Curve.GetEndPoint(0);
        var wallEnd = wallLoc.Curve.GetEndPoint(1);
        var wallMid = wallLoc.Curve.Evaluate(0.5, true);
        var wallRef = new Reference(wall);

        var newTag = IndependentTag.Create(document, view.Id, wallRef, true, tagMode, tagorn, wallMid);
        if (null == newTag) throw new Exception("Create IndependentTag Failed.");

        // newTag.TagText is read-only, so we change the Type Mark type parameter to 
        // set the tag text.  The label parameter for the tag family determines
        // what type parameter is used for the tag text.

        var type = wall.WallType;

        var foundParameter = type.LookupParameter("Type Mark");
        var result = foundParameter.Set("Hello");

        // set leader mode free
        // otherwise leader end point move with elbow point

        newTag.LeaderEndCondition = LeaderEndCondition.Free;
        var elbowPnt = wallMid + new XYZ(5.0, 5.0, 0.0);
        newTag.LeaderElbow = elbowPnt;
        var headerPnt = wallMid + new XYZ(10.0, 10.0, 0.0);
        newTag.TagHeadPosition = headerPnt;

        TaskDialog.Show("Create Independent Tag Method", "End Of Method Dialog");

        return newTag;
    }

    public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
    {
        throw new NotImplementedException();
    }

    #endregion
}

1 ответ

Решение

Вам необходимо вызвать метод CreateIndependentTag из метода Execute. Метод Execute - это то, что на самом деле вызывается Revit, и в настоящее время ваш метод выдает только исключение.

Кроме того, метод CreateIndependentTag ожидает стену, а также документ в качестве параметров. Документ можно получить из ExternalCommandData.
Стену можно получить, предложив пользователю выбрать стену, или взяв предварительно выбранную стену. В этом случае мы предложим пользователю выбрать стену и подтвердить выбор после этого.

Наконец, вам нужно обернуть вызов CreateIndependentTag в транзакции, так как вы вносите изменения в документ.

Собрать все вместе выглядит так:

public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
    {
        UIDocument uidoc = commandData.Application.ActiveUIDocument;
        Document doc = uidoc.Document;

        Reference reference;
        try
        {
            reference = uidoc.Selection.PickObject(ObjectType.Element, "Pick a wall");
        }
        catch
        {
            return Result.Cancelled;
        }

        var element = doc.GetElement(reference);

        if (element == null || !(element is Wall wall))
        {
            TaskDialog.Show("Error", "Selected element was not a wall");
            return Result.Failed;
        }

        using (Transaction trans = new Transaction(doc, "Creating tag"))
        {
            trans.Start();

            CreateIndependentTag(doc, wall);

            trans.Commit();
        }
    }

Несколько замечаний: было бы предпочтительно создать реализацию ISelectionFilter, чтобы ограничить выбор пользователя только стенами. Я также хотел бы сначала проверить существующий выбранный объект, используя uidoc.Selection.GetElementIds() чтобы убедиться, что стена уже выбрана, прежде чем предлагать пользователю выбрать ее. Блог Building Coder должен содержать множество примеров, связанных с этими двумя пунктами.

Другие вопросы по тегам