2015-08-19 77 views
2

所以我有一个文档,我正在通过WPF(C#)应用程序进行编辑。 我已成功编辑纯文本内容控件,但现在我卡住检查/取消选中表单中的复选框。设置OpenXml中的值复选框word2013

我成功找到该复选框并设置值并保存文档,但设置为true的复选框在打开文档时从不在文档内检查。

这里是我用来操纵复选框的代码。 注:我在标签级别访问复选框,因此field.parent.parent

private static void SetCheckBox(OpenXmlElement field, bool isChecked) 
{ 
    var checkBox = field.Parent.Parent.Descendants<SdtContentCheckBox>().ToList(); 
    foreach (var check in checkBox) 
    { 
     if (isChecked) 
     { 
      check.Checked.Val = OnOffValues.True; 
     } 
     else 
     { 
      check.Checked.Val = OnOffValues.False; 
     } 
     MessageBox.Show(check.Checked.Val); 
    } 
} 

当我在MessageBox中显示的值,他们真/假显示0/1。所以他们实际上正在设置。

我这样做是否正确?

回答

2

因此,不仅必须设置复选框的Checked值,而且必须更改Text值。

所以我最近的代码也有一些改变,但它改变了复选框的麻烦方面。

CODE:

private static void SetCheckBox(OpenXmlElement field, bool isChecked) 
{ 
    if (isChecked) 
    { 
     field.Parent.Parent.FirstChild.GetFirstChild<SdtContentCheckBox>().Checked.Val = OnOffValues.True; 
     field.Parent.Parent.Descendants<Run>().First().GetFirstChild<Text>().Text = "☒"; 
    } 
    else 
    { 
     field.Parent.Parent.FirstChild.GetFirstChild<SdtContentCheckBox>().Checked.Val = OnOffValues.False; 
     field.Parent.Parent.Descendants<Run>().First().GetFirstChild<Text>().Text = "☐"; 
    } 
} 

简明:

private static void SetCheckBox(OpenXmlElement field, bool isChecked) 
{ 
    field.Parent.Parent.FirstChild.GetFirstChild<SdtContentCheckBox>().Checked.Val = isChecked ? OnOffValues.True : OnOffValues.False; 
    field.Parent.Parent.Descendants<Run>().First().GetFirstChild<Text>().Text = isChecked ? "☒" : "☐"; 
} 
+0

这是解决问题了吗? –

+0

@MaximePorté是的,它是 – cmircovich

+0

你钉了它,谢谢! – Themos

1

的代码,另一个版本来解决此问题:

private void ResetFile(string filePath) 
    { 
     using (WordprocessingDocument doc = WordprocessingDocument.Open(filePath, true)) 
     { 
      try 
      { 
       string uncheckValue = "☐"; 
       string checkValue = "☒"; 

       foreach (SdtContentCheckBox ctrl in doc.MainDocumentPart.Document.Body.Descendants<SdtContentCheckBox>()) 
       { 
        if (ctrl.Checked.Val == OnOffValues.One) 
        { 
         ctrl.Checked.Val = OnOffValues.Zero; 
         if (ctrl.Parent.Parent.Descendants<SdtContentRun>().ToList().Count > 0) 
         { 
          SdtContentRun text = (SdtContentRun)ctrl.Parent.Parent.Descendants<SdtContentRun>().ToList()[0]; 
          text.InnerXml = text.InnerXml.Replace(checkValue, uncheckValue); 
         } 
        } 
       } 

       doc.MainDocumentPart.Document.Save(); 
      } 
      catch { } 
     } 
    }