Office JavaScript API: 绑定所选内容的子字符串

Office JavaScript API: Binding a substring of the selection

问题

在 MS Word 中使用 Office JavaScript API,我知道如何使用 document.bindings.addFromSelectionAsync 绑定当前选择,但是,我还没有找到绑定子字符串的方法当前选择。

例如,如果用户选择了整个段落,而我想只绑定第一个词,我该怎么做?

失败的方法

  1. 首先绑定选择,然后绑定子字符串,然后删除第一个绑定:我还没有找到绑定子字符串的方法。
  2. 先更改选择再使用addFromSelectionAsync: 我还没有找到更改选择的方法。

虽然不完全是您要找的东西,但 Word API 为您提供了完成此任务所需的大部分内容。

可以使用document.getSelection(). This returns a Range object. From here you can drill into Paragraphs, child ranges(基于分词规则)等获取用户的当前选择。

一旦您拥有反映您正在查找的文本的范围对象,range.Select() 将导致在 UI 中选择该范围。从这里您可以使用 addFromSelectionAsync 来建立您的绑定。

在 Word 中,Binding 在物理上由文档中的内容控件表示,因此通常的方法是在您需要的地方创建内容控件(在本例中为选择中的第一个单词)并为其指定一个标题,以便最终您可以使用 bindings.addFromNamedItem 方法创建绑定。

总结:

  1. 获取要创建绑定的范围。在这种情况下,您需要选择中的第一个词。
  2. 获得范围后,用内容控件将其包装起来并指定标题。
  3. 最后,使用带有该标题的 addFromNamedItem。

这是一个示例:

 Word.run(function (context) {
        //first we get the first word in the selection by using the split method, and using space as delimiter and then we add a content control
        var firstWordContentControl = context.document.getSelection().split([" "], true, false, true).getFirst().insertContentControl();
//let's add a title.
        firstWordContentControl.title = "BindingID";
        return context.sync()
            .then(function () { 
//we reuse the title to create the binding.
                Office.context.document.bindings.addFromNamedItemAsync("BindingID", "text", {}, function (result) {
                    console.log(result.status);
                    if (result.status == "succeeded") { 
                        // lets create an event!
                        result.value.addHandlerAsync(Office.EventType.BindingSelectionChanged, function () { 
                            console.log("event happened");
                        })
                    }
                 });
            })
    })
        .catch(function(exception) {
        OfficeHelpers.Utilities.log(exception);
    })

希望这对您有所帮助。 -娟