SliverNinja 上面的回答是正确的。在我移植了一些旧的 VB 代码之前,我忘记了你必须添加到集合中。我必须设置和读取一堆文档属性,所以这里有几个扩展方法可以从 Word 中的 BuiltInDocumentProperties 或 CustomDocumentProperties 读取/写入。这是 NetOffice 代码,但您可以通过更改 using 语句将其转换为 VSTO。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetOffice.OfficeApi;
using NetOffice.OfficeApi.Enums;
using NetOffice.WordApi;
namespace PalabraAddin {
public static class ExtDocument {
public static T GetCustomProperty<T>(this Document doc, string name, T defaultValue) {
return doc.GetProperty(doc.CustomDocumentProperties, name, defaultValue);
}
public static T GetBuiltInProperty<T>(this Document doc, string name, T defaultValue) {
return doc.GetProperty(doc.BuiltInDocumentProperties, name, defaultValue);
}
public static T SetCustomProperty<T>(this Document doc, string name, T value) {
return doc.SetProperty(doc.CustomDocumentProperties, name, value);
}
public static T SetBuiltInProperty<T>(this Document doc, string name, T value) {
return doc.SetProperty(doc.BuiltInDocumentProperties, name, value);
}
public static T GetProperty<T>(this Document doc, object collection, string name, T defaultValue) {
var properties = (DocumentProperties) collection;
foreach (var prop in properties.Where(prop => prop.Name == name))
return (T) prop.Value;
return defaultValue;
}
public static T SetProperty<T>(this Document doc, object collection, string name, T value) {
var properties = (DocumentProperties) collection;
foreach (var prop in properties.Where(prop => prop.Name == name)) {
if (!((T) prop.Value).Equals(value))
prop.Value = value;
return value;
}
MsoDocProperties propType;
if (value is Boolean)
propType = MsoDocProperties.msoPropertyTypeBoolean;
else if (value is DateTime)
propType = MsoDocProperties.msoPropertyTypeDate;
else if (value is double || value is Single)
propType = MsoDocProperties.msoPropertyTypeFloat;
else if (value is int)
propType = MsoDocProperties.msoPropertyTypeNumber;
else
propType = MsoDocProperties.msoPropertyTypeString;
properties.Add(name, false, propType, value);
return value;
}
}
}