更改功能区中按钮的标签添加字

change the Label of a button in ribbon word add in

我正在尝试创建一个简单的 Word 加载项。 我的功能区 a 已经创建了一个按钮,我想根据 word 文档的类型更改它的标签。 该文档是一个邮件合并,具有两种类型的模型:需求和响应。 我想要按钮标签:CREATE DEMAND for Demmand 和 CREATE RESPONSE for Response。

我试过类似的方法,但它不起作用:

 private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
        {

            Microsoft.Office.Interop.Word.Document doc = Globals.ThisAddIn.Application.ActiveDocument;
            //Word.MailMerge mailMerge = doc.MailMerge;

            if (doc.MailMerge.DataSource.FieldNames.Count!=0)
            {

                foreach (Microsoft.Office.Interop.Word.MailMergeFieldName f in doc.MailMerge.DataSource.FieldNames)
                {
                    if (f.Name.Equals("Response"))
                    {
                        this.button1.Label = "Create a response";
                        break;
                    }
                    else if (f.Name.Equals("Demand"))
                    {
                        this.button1.Label = "Create a demand";
                        break;
                    }
                }
            }
        }

doc.MailMerge.DataSource.FieldNames.Count 的值始终等于 0 你知道我该怎么做吗?

Word 中功能区的可视化设计器有点受限,您可以通过使用 XML 功能区获得更多功能,尽管它需要更多工作。

您可以通过创建两个按钮然后在功能区代码中创建一个 GetVisible 方法来处理此问题。 XML 如下:

<button id="ButtonCreateDemand" label="Create Demand"     size="normal"getVisible="GetVisible" onAction="Call_CreateDemand"/>
<button id="ButtonCreateResponse" label="Create Response" size="normal"getVisible="GetVisible" onAction="Call_CreateResponse"/>

代码应该是这样的

public bool GetVisible(Office.IRibbonControl control)
{
    //Check for demand\response

    switch(control.Id.ToLower())
    {
       case "buttoncreatedemand":
       return GetDemand();
       case "buttoncreateresponse":
       return !GetDemand();           
    }

}

private bool GetDemand()
{
     Microsoft.Office.Interop.Word.Document doc = Globals.ThisAddIn.Application.ActiveDocument;
        //Word.MailMerge mailMerge = doc.MailMerge;

        if (doc.MailMerge.DataSource.FieldNames.Count!=0)
        {

            foreach (Microsoft.Office.Interop.Word.MailMergeFieldName f in doc.MailMerge.DataSource.FieldNames)
            {
                if (f.Name.Equals("Response"))
                {
                    return false;
                }
            }
        }
        return true;
}

或者,您可以使用 GetLabel() 方法来 return 按钮的标签。

您将 DocumentChange() 事件添加到 ThisAddIn class

    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        Globals.ThisAddIn.Application.DocumentChange += new Word.ApplicationEvents4_DocumentChangeEventHandler(DocumentChange);
    }