我创建了许多TextElement,需要对部分文字进行替换,代码如何实现呢?我已经能获取到TextBlock了,TextBlock提供有Replace函数,但不知道如何查找到要替近换的内容。
获取TextBlock中的文字内容,用C# 字符串操作函数去查找和替换。然后用创建的Text去Replace这个TextBlock。
-------------------------------------------------------------------
在C++的TextBlock下有专门的FindTextParameters和FindTextMatch两个类可用于此目的,但可惜的是.NET未做封装,C# 中无法使用。
TextQueryOptions queryOps = new TextQueryOptions(); List<Element> signatureElements = DgnHelper.GetElementsFromCell(libFileName, cellName); foreach (Element element in signatureElements) { if (element is TextElement) { TextElement text = element as TextElement; TextPartIdCollection tids = text.GetTextPartIds(queryOps); foreach (TextPartId tid in tids) { TextBlock block = text.GetTextPart(tid); string str = block.ToString(); str.Replace("{图号}", drawingNumber); block.ReplaceText(str, block.CreateStartCaret(), block.CreateEndCaret()); } } } CellHeaderElement cell = new CellHeaderElement(dgnModel, cellName, DPoint3d.Zero, DMatrix3d.Identity, signatureElements); DTransform3d t3d = DTransform3d.FromTranslation(new DPoint3d(w, y0, 0) * uor); cell.ApplyTransform(new TransformInfo(t3d)); cell.AddToModel();
问题1、TextBlock仅仅是内存中的表达,你调用了ReplaceText后仅仅是将内存中的文字内容作了修正,并未反映到实际的TextElement上面去,需要调用TextHandlerBase::CreateElement根据这个新的TextBlock创建一个新的TextElement。仍后去ReplaceInModel老的TextElement
问题2、我发现您的Text还是位于Cell中的,那这个情况就更复杂了,需要ReplaceInModel的是Cell,而不能重新的重建一个新Cell,AddToModel。只有新建才是调用AddToModel,而修改则是需要ReplaceInModel。
您先把问题1处理正确再说。即先用独立的文字元素做测试,仍后再进一步研究Cell中的Text的修改。
Answer Verified By: lingwei liu
嗯,按您的思路,重新编写了代码,基本实现了。感谢符老师。以下代码供网友参考:
using (ElementCopyContext copyContext = new ElementCopyContext(dgnModel)) { TransformInfo transform = new TransformInfo(DTransform3d.FromTranslation(new DPoint3d(w, y0, 0) * uor)); TextQueryOptions queryOps = new TextQueryOptions(); List<Element> signatureElements = DgnHelper.GetElementsFromCell(libFileName, cellName); foreach (Element element in signatureElements) { if (element is TextElement) { TextElement text = element as TextElement; TextPartIdCollection partIds = text.GetTextPartIds(queryOps); foreach (TextPartId partId in partIds) { TextBlock block = text.GetTextPart(partId); string str = block.ToString(); str = str.Replace("{图号}", drawingNumber); block.ReplaceText(str.Replace("{图号}", drawingNumber), block.CreateStartCaret(), block.CreateEndCaret()); text.ReplaceTextPart(partId, block); } } element.ApplyTransform(transform); copyContext.DoCopy(element); } }