2

我正在使用 JavaScript API for Office、MS Word 2016、VisualStudio 2015 进行开发。文档中有多个具有相同标题的富文本 ContentContols。我正在尝试将这些 ContentControls 绑定到处理程序,以便我可以获得 onBindingDataChanged 通知。

有没有办法将 ContentControls 绑定到一个具有自己 ID 的处理程序?或将 ContentControls 的 id 作为一个参数传递?

我目前的代码是这样的:

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);     
    }

由于文档中有多个标题为“CCTitle”的内容控件,addFromNamedItemAsync在函数中bindNamedItem会报错:Multiple objects with the same name were found.

我想要实现的是在用户对它们中的任何一个进行一些更改时获取 ContentControls 的 id 和内容。有什么想法可以帮忙吗?提前致谢。

4

1 回答 1

0

正如您所发现的,内容控件的命名会阻止您基于名称进行绑定。但是,您可以使用一种解决方法来绑定到每个内容控件

  1. 首先检索Document .contentControls,它返回一个包含文档中所有内容控件的数组,称为ContentControlCollection
  2. 数组中的每个元素都是一个ContentControl 对象。为每个 ContentControl 依次执行步骤 3-6:
  3. 使用 contentControl.title 检查 ContentControl 的名称。如果它与您要查找的名称 (CCTitle) 匹配,则继续执行以下步骤。否则从第 3 步开始返回下一个 ContentControl。
  4. 使用默认参数调用 ContentControl 的select() 方法以使 word 选择它。
  5. 在回调中收到选择 ContentControl 的确认后,使用 Text bindingType调用Bindings.addFromSelectionAsync() 。
  6. 在回调中收到成功创建Binding的确认后,使用 BindingDataChanged EventType调用Binding.addHandlerAsync。如果您愿意,使用可以对所有这些绑定使用相同的处理函数。

这种变通方法的缺点之一是有许多链式异步调用,因此性能可能不如您希望的那么快。因此,我建议将此操作绑定到某些用户操作和/或在任务窗格中添加加载 UI 以避免混淆用户。

-Michael(Office 插件的 PM)

于 2016-04-25T18:30:00.047 回答