【问题标题】:How to get exact cursor position in RichTextbox to display Popup如何在 RichTextbox 中获取准确的光标位置以显示 Popup
【发布时间】:2014-01-29 18:10:24
【问题描述】:

我想在 WPF 中显示 RichTextBox 的 POPUP 特定位置。我知道有一种方法可以通过以下代码行在 winforms RichTextBox 中获得相同的效果。

Point point = richTextBox1.GetPositionFromCharIndex(richTextBox1.SelectionStart);

【问题讨论】:

    标签: wpf richtextbox cursor-position


    【解决方案1】:

    我想这取决于您弹出的时间和内容。 MSDN 中的一个示例显示了如何在RichTextBox 控件中使用选定文本的位置定位ContextMenuHow to: Position a Custom Context Menu in a RichTextBox 有趣的是下面的代码:

    TextPointer position = rtb.Selection.End;
    
    if (position == null) return;
    
    Rect positionRect = position.GetCharacterRect(LogicalDirection.Forward);
    contextMenu.HorizontalOffset = positionRect.X;
    contextMenu.VerticalOffset = positionRect.Y;
    

    这会获取选择的相对位置。如果您要弹出一个表单,则需要将其转换为 Window 位置。

    这是我用来测试在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 Behavior 文章,就Popup 行为而言,这可能是您正在寻找的内容。您可以将我上面提供的代码与 RichTextBox 的选择或插入符号位置一起使用,然后确定Popup 的最终定位。我希望这会有所帮助。

    【讨论】:

      【解决方案2】:
          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);}}}
      

      【讨论】:

      • 你能解释一下你的答案吗?
      猜你喜欢
      • 2012-05-05
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-25
      相关资源
      最近更新 更多