How to determine hyperlink coordinates in WPF

I have a WPF window with a FlowDocument with a few hyperlinks in it:

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

In C # code, I handle the Click event to create and display a new WPF window:

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

I need this window to appear next to the actual position of the hyperlink. Therefore, I assume that for this it is necessary to assign values ​​to the Left and Top properties of the window. But I do not know how to get the position of the hyperlink.

+3
source share
1 answer

ContentStart ContentEnd, 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;
}
+4

Source: https://habr.com/ru/post/1763351/


All Articles