Revit通过API创建共享参数
Revit共享参数是通过创建一个.txt类型的文件来保存相关信息,一旦与项目保存完毕之后,共享参数也就变成了项目参数(项目参数无法通过API创建),项目参数是保存在Revit项目里面的,所以此时这个.txt文件是可以删除的。
1 using Autodesk.Revit.DB; 2 using System; 3 using System.IO; 4 using System.Reflection; 5 6 namespace HelloRevit 7 { 8 public class RevitApiUtils 9 { 10 /// <summary> 11 /// 创建共享参数 12 /// </summary> 13 /// <param name="doc">Document对象</param> 14 /// <param name="groupName">共享参数组名</param> 15 /// <param name="definitionName">共享参数名</param> 16 /// <param name="builtInCategory">需要参数绑定的类型</param> 17 /// <param name="builtInParameterGroup">参数所属的属性类型</param> 18 /// <param name="parameterType">参数数据类型</param> 19 /// <param name="isInstanceParameter">是否实例参数</param> 20 public static void AddSharedParameters(Document doc, string groupName, string definitionName, BuiltInCategory builtInCategory, BuiltInParameterGroup builtInParameterGroup, ParameterType parameterType, bool isInstanceParameter) 21 { 22 var assemblyPath = Assembly.GetExecutingAssembly().Location; 23 var index = assemblyPath.IndexOf("\\", StringComparison.Ordinal); 24 var rootPath = assemblyPath.Substring(0, index); 25 var sharedParameterPath = Path.Combine(rootPath, "RevitSharedParameters.txt"); 26 if (File.Exists(sharedParameterPath)) 27 { 28 File.Delete(sharedParameterPath); 29 } 30 var categorySet = new CategorySet(); 31 var category = doc.Settings.Categories.get_Item(builtInCategory); 32 categorySet.Insert(category); 33 if (!File.Exists(sharedParameterPath)) 34 { 35 try 36 { 37 File.Create(sharedParameterPath); 38 } 39 catch (Exception) 40 { 41 ThrowNewException("异常!"); 42 } 43 } 44 //设置共享参数文件 45 doc.Application.SharedParametersFilename = sharedParameterPath; 46 //打开共享参数文件 47 var definitionFile = doc.Application.OpenSharedParameterFile(); 48 if (definitionFile == null) 49 { 50 ThrowNewException("无法打开共享参数文件"); 51 return; 52 } 53 //获取共享参数组 54 var definitionGroups = definitionFile.Groups; 55 //获取参数组 56 var group = definitionGroups.get_Item(groupName) ?? definitionGroups.Create(groupName); 57 if (group == null) 58 { 59 ThrowNewException("创建共享参数组失败!"); 60 return; 61 } 62 63 //获取参数定义 64 var definition = group.Definitions.get_Item(definitionName); 65 if (definition == null) 66 { 67 var externalDefinitionCreationOptions = new ExternalDefinitionCreationOptions(definitionName, parameterType); 68 definition = group.Definitions.Create(externalDefinitionCreationOptions); 69 } 70 71 ElementBinding binding; 72 if (isInstanceParameter) 73 { 74 binding = doc.Application.Create.NewInstanceBinding(categorySet); 75 } 76 else 77 { 78 binding = doc.Application.Create.NewTypeBinding(categorySet); 79 } 80 81 bool isSuccess = doc.ParameterBindings.Insert(definition, binding, builtInParameterGroup); 82 83 if (!isSuccess) 84 { 85 ThrowNewException("共享参数绑定失败!"); 86 } 87 88 //删除共享参数txt文件,从某种意义上讲,绑定之后的共享参数就变成了项目参数只针对当前项目存在 89 File.Delete(sharedParameterPath); 90 } 91 92 public static void ThrowNewException(string msg) 93 { 94 throw new Exception(msg); 95 } 96 97 } 98 }