2011-04-13 77 views
8

是否可以链接到WPF文本块的Word文档中的书签?超链接到MS Word文档中的书签

到目前为止,我有:

<TextBlock TextWrapping="Wrap" FontFamily="Courier New"> 
    <Hyperlink NavigateUri="..\\..\\..\\MyDoc.doc"> My Word Document </Hyperlink> 
</TextBlock> 

我假设的相对路径是exe文件的位置。我无法让文档打开。

回答

5

作为我以前的答案的补充,有一种编程方式打开本地Word文件,搜索书签并将光标放置在那里。我改编自this excellent answer。如果你有这样的设计:

<TextBlock>   
    <Hyperlink NavigateUri="..\\..\\MyDoc.doc#BookmarkName" 
       RequestNavigate="Hyperlink_RequestNavigate"> 
     Open the Word file 
    </Hyperlink>    
</TextBlock> 

使用此代码:

//Be sure to add this reference: 
//Project>Add Reference>.NET tab>Microsoft.Office.Interop.Word 

private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e) { 
    // split the given URI on the hash sign 
    string[] arguments = e.Uri.AbsoluteUri.Split('#'); 

    //open Word App 
    Microsoft.Office.Interop.Word.Application msWord = new Microsoft.Office.Interop.Word.Application(); 

    //make it visible or it'll stay running in the background 
    msWord.Visible = true; 

    //open the document 
    Microsoft.Office.Interop.Word.Document wordDoc = msWord.Documents.Open(arguments[0]); 

    //find the bookmark 
    string bookmarkName = arguments[1]; 

    if (wordDoc.Bookmarks.Exists(bookmarkName)) 
    { 
     Microsoft.Office.Interop.Word.Bookmark bk = wordDoc.Bookmarks[bookmarkName]; 

     //set the document's range to immediately after the bookmark. 
     Microsoft.Office.Interop.Word.Range rng = wordDoc.Range(bk.Range.End, bk.Range.End); 

     // place the cursor there 
     rng.Select(); 
    } 
    e.Handled = true; 
} 
4

在WPF应用程序而不是网页中使用超链接需要您自己处理RequestNavigate事件。

有一个很好的例子here

+0

有处理的超级链接本身,但似乎并没有处理书签的例子。 – 2013-04-30 23:50:26

3

按照official documentation,它应该是出奇的简单:

<TextBlock>   
<Hyperlink NavigateUri="..\\..\\MyDoc.doc#BookmarkName" 
    RequestNavigate=”Hyperlink_RequestNavigate”> 
    Open the Word file 
</Hyperlink>    
</TextBlock> 

private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e) 
    { 
      Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri)); 
      e.Handled = true; 
    } 

然而,在a lotof inofficial页面,这只能

  • .doc文件(没有Office 2007 .docx共识文件),不幸的是
  • 只与Office 2003

试图将此与.docx文件一起使用会产生错误。在Office 2007及更高版本上使用.doc文件将打开该文档,但会打开第一页。

通过使用AutoOpen宏,您可能能够解决Office 2007及更高版本的局限性,请参阅此处了解如何将Word。这将需要更改与该系统一起使用的所有文档(并提出有关使用宏的其他问题)。

+0

赞成票,你有一个美好的继续和权力活动的堆栈。 – 2013-05-07 12:31:09