当你add VSTO(非 Word 原生)content control ,您指定名称:
controls.AddContentControl(wordRange, "foo", wdType);
其中控件是 VSTO(扩展)Document.Controls 集合。
以后可以look up按名称控制:
ContentControl myContentControl = controls["foo"];
那么为什么 ContentControl 没有 Name 属性呢? (或 ContentControlBase,或任何其他衍生产品)。
我正在为 Document.Controls 属性实现一个包装类,它允许您添加或迭代内容控件。迭代底层 Document.Controls 时,无法查找每个控件的名称。 (我们需要它来返回我们的 ContentControl 包装器的一个实例)。所以目前我正在我们的 ContentControls 包装类中这样做:
public IEnumerator<IContentControl> GetEnumerator()
{
System.Collections.IEnumerator en = this.wordControls.GetEnumerator();
while (en.MoveNext())
{
// VSTO Document.Controls includes all managed controls, not just
// VSTO ContentControls; return only those.
if (en.Current is Microsoft.Office.Tools.Word.ContentControl)
{
// The control's name isn't stored with the control, only when it was added,
// so use a placeholder name for the wrapper.
yield return new ContentControl("Unknown", (Microsoft.Office.Tools.Word.ContentControl)en.Current);
}
}
}
我宁愿不必求助于在我们的 ContentControls 对象中保留名称到包装对象的映射。谁能告诉我如何获取控件的名称(传递给 Controls.Add() 的名称参数?
请您参考如下方法:
当您以编程方式添加 CC 然后需要在同一 Word 实例期间立即访问它时,“名称”参数纯粹是为了便于操作。事后访问 CC 是通过 ContentControl.ID 属性中的 GUID。因此,从这个意义上说,“名称”对于以后的访问和操作毫无用处,因为它没有保留在 WordprocessingML 标记中。
一种更简单的方法是完全忽略“名称”指定,添加一个 CC,获取它的 .ID 然后使用它。诚然,Guid 对人类读者来说毫无意义,但您的程序应该能够解释它。
如果您确实需要通过一个有意义的名称获取 CC,例如“foo”,只需使用 .Tag 属性作为您的 CC 的名称(它只需要对于每个 CC 都是唯一的尽管您的标签用作名称)并通过标签查询 ContentControlCollection。
