2010-09-05 54 views
3

我有它的WPF窗口中出現了FlowDocument的幾個鏈接:如何確定一個超鏈接的座標在WPF

<FlowDocumentScrollViewer> 
    <FlowDocument TextAlignment="Left" > 
    <Paragraph>Some text here 
     <Hyperlink Click="Hyperlink_Click">open form</Hyperlink> 
    </Paragraph>   
    </FlowDocument> 
</FlowDocumentScrollViewer> 

在C#代碼我處理Click事件來創建並顯示一個新的WPF窗口:

private void Hyperlink_Click(object sender, RoutedEventArgs e) 
{ 
    if (sender is Hyperlink) 
    { 
     var wnd = new SomeWindow(); 
     //wnd.Left = ??? 
     //wnd.Top = ??? 
     wnd.Show(); 
    } 
} 

我需要這個窗口出現旁邊超鏈接的實際位置。所以我假設它需要給窗口的Left和Top屬性賦值。但我不知道如何獲得超鏈接的位置。

回答

4

您可以使用ContentStartContentEnd獲取超鏈接開頭或結尾的TextPointer,然後調用GetCharacterRect以獲取相對於FlowDocumentScrollViewer的邊界框。如果您獲得對FlowDocumentScrollViewer的引用,則可以使用PointToScreen將其轉換爲屏幕座標。

private void Hyperlink_Click(object sender, RoutedEventArgs e) 
{ 
    var hyperlink = sender as Hyperlink; 
    if (hyperlink != null) 
    { 
     var rect = hyperlink.ContentStart.GetCharacterRect(
      LogicalDirection.Forward); 
     var viewer = FindAncestor(hyperlink); 
     if (viewer != null) 
     { 
      var screenLocation = viewer.PointToScreen(rect.Location); 

      var wnd = new Window(); 
      wnd.WindowStartupLocation = WindowStartupLocation.Manual; 
      wnd.Top = screenLocation.Y; 
      wnd.Left = screenLocation.X; 
      wnd.Show(); 
     } 
    } 
} 

private static FrameworkElement FindAncestor(object element) 
{ 
    while(element is FrameworkContentElement) 
    { 
     element = ((FrameworkContentElement)element).Parent; 
    } 
    return element as FrameworkElement; 
} 
+0

非常感謝。有用。 – 2010-09-05 19:12:36