2010-09-05 7 views
3

Je fenêtre WPF avec un FlowDocument avec plusieurs hyperliens il:Comment puis-je déterminer les coordonnées d'un lien hypertexte dans WPF

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

Dans le code C# Je gère Cliquez événement pour créer et afficher une nouvelle WPF fenêtre:

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

J'ai besoin cette fenêtre apparaître à côté de la position réelle de lien hypertexte. Je suppose donc qu'il faut assigner des valeurs aux propriétés Left et Top de la fenêtre. Mais je n'ai aucune idée de la façon d'obtenir une position de lien hypertexte.

Répondre

4

Vous pouvez utiliser ContentStart ou ContentEnd pour obtenir un TextPointer pour le début ou la fin de l'hyperlien, puis appelez GetCharacterRect pour obtenir la zone de délimitation par rapport à la FlowDocumentScrollViewer. Si vous obtenez une référence à FlowDocumentScrollViewer, vous pouvez utiliser PointToScreen pour le convertir en coordonnées d'écran.

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

Merci beaucoup. Ça marche. –