How do I unlock a content control using the OpenXML SDK in a Word 2010 document?
The openxml SDK provides the Lock
class and the LockingValues
enumeration
for programmatically setting the options:
- Content control cannot be deleted and
- Contents cannot be edited
So, to set those two options to "false" (LockingValues.Unlocked
),
search for all SdtElement
elements in the document and set the Val
property to
LockingValues.Unlocked
.
The code below shows an example:
static void UnlockAllSdtContentElements()
{
using (WordprocessingDocument wordDoc =
WordprocessingDocument.Open(@"c:\temp\myword.docx", true))
{
IEnumerable<SdtElement> elements =
wordDoc.MainDocumentPart.Document.Descendants<SdtElement>();
foreach (SdtElement elem in elements)
{
if (elem.SdtProperties != null)
{
Lock l = elem.SdtProperties.ChildElements.First<Lock>();
if (l == null)
{
continue;
}
if (l.Val == LockingValues.SdtContentLocked)
{
Console.Out.WriteLine("Unlock content element...");
l.Val = LockingValues.Unlocked;
}
}
}
}
}
static void Main(string[] args)
{
UnlockAllSdtContentElements();
}