C# VSTO word AddIn Throws 值不在预期错误范围内

C# VSTO word AddIn Throws value does not fall within expected error

本人初学VSTO word Addin,最终目标是查看自定义文档属性 exists.Read网上所有可用文章无突破

从此代码开始

public void chk()
{
   if (this.Application.ActiveDocument.CustomDocumentProperties["ObjectType"].Value = 0)
   {
      MessageBox.Show("Please select an object");
   }
}

这会引发错误

Value does not fall within bounds error

修改了代码以创建自定义文档 属性 对象,如下所示,它在

上给了我同样的错误

if(this.Application.ActiveDocument.CustomDocumentProperties["ObjectType"].Value = 0)

public void chk()
{
      dynamic properties = null;
      properties = this.Application.ActiveDocument.CustomDocumentProperties;
      properties.Add("Name",false,Office.MsoDocProperties.msoPropertyTypeString, "ObjectType");
      properties.Add("LinkToContent",false, Office.MsoDocProperties.msoPropertyTypeBoolean,false);
      properties.Add("Type",false,Office.MsoDocProperties.msoPropertyTypeNumber, 0);
                   
      if(this.Application.ActiveDocument.CustomDocumentProperties["ObjectType"].Value = 0)
      {
          MessageBox.Show("Please select an object");
       }
}

请求您建议解决问题的步骤。如果需要更多信息,请告诉我。

您可以遍历所有属性并检查它们的名称,比较两种方法:

void TestProperties()
{
    Microsoft.Office.Core.DocumentProperties properties;
    properties = (Office.DocumentProperties)this.CustomDocumentProperties;

    if (ReadDocumentProperty("Project Name") != null)
    {
        properties["Project Name"].Delete();
    }

    properties.Add("Project Name", false,
        Microsoft.Office.Core.MsoDocProperties.msoPropertyTypeString,
        "White Papers");
}

private string ReadDocumentProperty(string propertyName)
{
    Office.DocumentProperties properties;
    properties = (Office.DocumentProperties)this.CustomDocumentProperties;

    foreach (Office.DocumentProperty prop in properties)
    {
        if (prop.Name == propertyName)
        {
            return prop.Value.ToString();
        }
    }
    return null;
}