我有一个带有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属性赋值。但我不知道如何获得超链接位置。
答案 0 :(得分:4)
您可以使用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;
}