采用族管理的AddParameter方法
//选中一根梁 Reference beamRef = uiDoc.Selection.PickObject(ObjectType.Element); FamilyInstance beam = doc.GetElement(beamRef) as FamilyInstance; //获取族文档 Document familyDoc = doc.EditFamily(beam.Symbol.Family); if(familyDoc==null||!familyDoc.IsFamilyDocument) { return Result.Cancelled; } //获取族管理器 FamilyManager familyManager = familyDoc.FamilyManager; //共享族的基本信息,包括定义路径文件,参数分组名称,参数名称,参数类型 string sharedParameterFilePath = @"D:\ShareParameter.txt"; string sharedParameterGroupName = "Shared_Group"; string sharedParameter = "UserDefineParameter4"; ParameterType sharedParameterType = ParameterType.Length; //打开或者创建共享参数文件 if(!File.Exists(sharedParameterFilePath)) { try { FileStream fs = File.Create(sharedParameterFilePath); fs.Close(); } catch(Exception e) { MessageBox.Show("共享参数文件创建失败!"); return Result.Cancelled; } } app.SharedParametersFilename = sharedParameterFilePath; DefinitionFile sharedDefinitionFile = app.OpenSharedParameterFile(); if(sharedDefinitionFile==null) { MessageBox.Show("无法打开共享参数文件!"); return Result.Cancelled; } DefinitionGroup sharedGroup = null; sharedGroup = sharedDefinitionFile.Groups.get_Item(sharedParameterGroupName); if (sharedGroup == null) sharedGroup = sharedDefinitionFile.Groups.Create(sharedParameterGroupName); //查找共享参数的定义,如果找不到就利用名字和类型创建一个 ExternalDefinition parameterDef = sharedGroup.Definitions.get_Item(sharedParameter) as ExternalDefinition; if (null == parameterDef) { ExternalDefinitionCreationOptions externalDefinitionCreationOptions = new ExternalDefinitionCreationOptions(sharedParameter, sharedParameterType); parameterDef = sharedGroup.Definitions.Create(externalDefinitionCreationOptions) as ExternalDefinition; } //创建共享族参数 TransactionWrapper trans = new TransactionWrapper(familyDoc, "t1"); FamilyParameter parameter = familyManager.get_Parameter(parameterDef); if(parameter==null) { MessageBox.Show("无法获取自定义参数,将自动添加"); FamilyParameter newParameter = familyManager.AddParameter(parameterDef, BuiltInParameterGroup.PG_GENERAL, false); } else { MessageBox.Show("参数:"+parameter.Definition.Name); } trans.Commit(); //将编辑后的族导入文档 familyDoc.LoadFamily(doc,new familyLoadOptions()); MessageBox.Show("族实例参数添加成功");其中编辑好的族要再次导入到文档中,需要提供一个导入选项IFamilyLoadOptions
class familyLoadOptions : IFamilyLoadOptions { public bool OnFamilyFound(bool familyInUse, out bool overwriteParameterValues) { overwriteParameterValues = true; return true; } public bool OnSharedFamilyFound(Family sharedFamily, bool familyInUse, out FamilySource source, out bool overwriteParameterValues) { source = FamilySource.Project; overwriteParameterValues = true; return true; } }