/// <summary> /// 给单元对象的子对象添加自定义属性 /// </summary> /// <param name="cellEl"></param> private void AddCellChildProperty(CellHeaderElement cellEl) { ChildElementCollection elements = cellEl.GetChildren(); foreach (var el in elements) { var itemlibrary = ItemTypeLibrary.FindByName("库名1", Session.Instance.GetActiveDgnFile()); var itemType = itemlibrary.GetItemTypeByName("属性类型"); var host = new CustomItemHost(el, true); var instance = host.GetCustomItem("库名1", "属性类型"); if (null == instance) { instance = host.ApplyCustomItem(itemType); } instance.IsReadOnly = true; // instance.WriteChanges(); instance.ScheduleChanges(el); el.ReplaceInModel(el);//崩溃 cellEl.ReplaceInModel(el);//也会崩溃 } }
.NET C# 对ChildElement的封装确实有Bug,请改用C++ 或Interop那套C# 试一下。
符老师,您好,Interop我也测试过了,也是不行。现在就差用C++了。C++我这块还没积累,能不能用混合编程封装一个,供C#调用呢。
Interop可以替换,但是不能添加属性。用添加属性的子对象替换当前对象时,属性信息会丢失,只替换了模型对象。
请给我点时间,我写一个测试代码验证一下。
谢谢符老师
如下测试代码可以正确执行:
using BIM = Bentley.Interop.MicroStationDGN; using BMI = Bentley.MstnPlatformNET.InteropServices; ... ... private static void AddItemToChildInCell() { BIM.Application app = BMI.Utilities.ComApp; BIM.CellElement myCell = app.ActiveModelReference.GetElementByID64(11389L) as BIM.CellElement; myCell.ResetElementEnumeration(); int nestDepth = 0; while (myCell.MoveToNextElement(true, ref nestDepth)) { BIM.Element tempEl = myCell.CopyCurrentElement(); if (tempEl.IsEllipseElement()) { BIM.ItemTypeLibraries itemTypeLibraries = new BIM.ItemTypeLibrariesClass(); BIM.ItemTypeLibrary itemTypeLib = itemTypeLibraries.FindByName("MyLib"); BIM.ItemType itemType = itemTypeLib.GetItemTypeByName("MyType"); itemType.AttachItem(tempEl); myCell.ReplaceCurrentElement(tempEl); } } myCell.Rewrite(); }
我用了系统标准的单元库中的NORTH单元,该单元里面只有一个文字和一个圆。我的代码仅对圆这个子元素挂了我自定义的一个ItemType。
MS学习资源:
MicroStation Wednesday视频分享
深入探讨MicroStation DGN基本概念系列
一步步学习MicroStation CE Addin开发
一步步学习MicroStation CE MDL开发
谢谢符老师,已经使用!
请阅读置顶的【发帖指南】。在得到正确答案后协助我们确认答案。