How to Bind one handler to multiple ContentControls (with same title) in Word? Use Javascript API for Office

时间:2016-04-04 18:45:04

标签: ms-office contentcontrol office-js officedev javascript-api-for-office

I'm developing with JavaScript API for Office, MS Word 2016, VisualStudio 2015. There are multiple Rich Text ContentContols with a same title in the document. I'm trying to bind these ContentControls to a handler so that I can get onBindingDataChanged notification.

Is there a way to bind the ContentControls to one handler with their own ID? or pass ContentControls' id as one parameter?

My current code is like:

function bindNamedItem() {

    Office.context.document.bindings.addFromNamedItemAsync("CCTitle", Office.BindingType.Text, { id: 'ccbind' }, function (result) {
        if (result.status == 'succeeded') {
            console.log('Added new binding with type: ' + result.value.type + ' and id: ' + result.value.id);
        }
        else
            console.log('Error: ' + result.error.message);
    });

}
 function addEventHandlerToBinding() {
    Office.select("bindings#ccbind").addHandlerAsync(Office.EventType.BindingDataChanged, onBindingDataChanged);
}

 var onBindingDataChanged = function (result) {
        console.log(result);     
    }

Since there are multiple contentcontrols in the document with title "CCTitle", addFromNamedItemAsync in function bindNamedItem will give error: Multiple objects with the same name were found.

What I'm trying to achieve is to get the ContentControls' id and content whenever the user make some change to any of them. Is there any idea to help? Thanks in advance.

1 个答案:

答案 0 :(得分:0)

正如您所发现的,内容控件的命名会阻止您根据名称进行绑定。但是,可用于绑定到每个内容控件的变通方法:

  1. 首先检索Document。contentControls,它返回文档中名为ContentControlCollection的所有内容控件的数组。
  2. 数组中的每个元素都是ContentControl object。按顺序执行每个ContentControl的步骤3-6:
  3. 使用contentControl.title检查ContentControl的名称。如果它与您正在寻找的名称(CCTitle)匹配,则继续执行以下步骤。否则,请在步骤3中返回下一个ContentControl。
  4. 使用默认参数调用ContentControl' select() method,以便选择它。
  5. 一旦您在回调中收到ContentControl被选中的确认,请使用Text bindingType调用Bindings.addFromSelectionAsync()
  6. 在回调中收到确认已成功创建Binding后,请使用BindingDataChanged Binding.addHandlerAsync致电EventType。如果您愿意,可以对所有这些绑定使用相同的处理函数。
  7. 此解决方法的一个缺点是存在许多链式异步调用,因此性能可能不如您所希望的那么快。因此,我建议将此操作绑定到某些用户操作和/或在任务窗格中添加加载UI,以避免混淆用户。

    -Michael(PM for Office加载项)