c# - 如何确定 WPF 中超链接的坐标

标签 c# .net wpf flowdocument

我有一个带有 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 属性赋值。但我不知道如何获得超链接位置。

最佳答案

您可以使用 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;
}

关于c# - 如何确定 WPF 中超链接的坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3647263/

相关文章:

c# - 如何使用 Selenium Webdriver 查找没有 id 属性的 div 元素

c# - 将 ServiceStack 从 3.9.8 升级到 3.9.70 后出现 404(新 API)

c# - 在WPF MVVM中,如何在运行时从文本框值调整图像大小?

.NET Repeater - 自定义服务器验证

c# - ILOnly = 0 是否表示 C++/CLI?

wpf - 暂停对绑定(bind) ObservableCollection<T> 的 DataGrid 的更新

wpf - MVVM 和多窗口

c# - Visual Studio 在具有服务器 IP 的本地计算机上运行

c# - 来自数据库或代码的 DropDownListFor 枚举的 MVC4 最佳实践

c# - 从 AWS S3 读取流涉及加载整个文件