我想在WPF中显示RichTextBox的POPUP特定位置。我知道有一种方法可以通过以下代码行在 winforms RichTextBox 中获得相同的结果。
Point point = richTextBox1.GetPositionFromCharIndex(richTextBox1.SelectionStart);
我想这取决于你出现的时间和内容。 MSDN 中的一个示例显示了如何将
ContextMenu
与 RichTextBox
控件中所选文本的位置一起定位。
如何:在 RichTextBox 中放置自定义上下文菜单
有趣的是下面的代码:
TextPointer position = rtb.Selection.End;
if (position == null) return;
Rect positionRect = position.GetCharacterRect(LogicalDirection.Forward);
contextMenu.HorizontalOffset = positionRect.X;
contextMenu.VerticalOffset = positionRect.Y;
这将获取所选内容的相对位置。如果您要弹出一个表单,您需要将其转换为窗口位置。
这是我用来测试在
RichTextBox
中所选文本上加载弹出窗口的一段代码。这还考虑到多个显示器。
TextPointer tp = txtEditor.Selection.End;
if (tp == null) return;
Rect charRect = tp.GetCharacterRect(LogicalDirection.Forward);
Point winPoint = txtEditor.PointToScreen(charRect.TopRight);
Popup p = new Popup();
p.Left = winPoint.X;
p.Top = winPoint.Y;
p.Show();
更新: 我做了一些额外的研究,发现一篇 MSDN Popup Placement Behaviour 文章很可能就是您正在寻找的
Popup
行为。您可以使用我上面提供的代码以及 RichTextBox 的选择或插入符号位置来确定 Popup
的最终位置。我希望这有帮助。
static void tb_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.KeyStates == ((e.KeyStates ^ System.Windows.Input.KeyStates.Down)^System.Windows.Input.KeyStates.Down))
{
if (e.Key == System.Windows.Input.Key.OemPeriod)
{
TextBox tb = (TextBox)sender;
Rect r = tb.GetRectFromCharacterIndex(tb.CaretIndex, true);
Point p = tb.TransformToAncestor(tb).Transform(new Point(r.X, r.Y + 10));
p = tb.PointToScreen(p);
Rect rect = new Rect(p.X, p.Y, 0, 0);
Grid g = (Grid)Application.Current.MainWindow.Content;
System.Windows.Controls.Primitives.Popup popup = new System.Windows.Controls.Primitives.Popup();
popup.SetValue(System.Windows.Controls.Primitives.Popup.PlacementRectangleProperty, rect);
popup.IsOpen = true;
g.Children.Add(popup);
}
}
}