Show ToolTip on RichTextBox

2020-08-01 08:34发布

问题:

I have a RichTextBox on a WPF Window. Now, I want to show a ToolTip when the user move the mouse over the RichTextBox. The Content of the RichTextBox should depend on the Text which is under the mouse pointer. For this I should get the position of the char, on which the mouse shows to.

Best Regards, Thomas

回答1:

In the following example the tooltip will show the next character where the caret is.

Xaml:

<Window x:Class="Test.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
  <RichTextBox ToolTipOpening="rtb_ToolTipOpening" ToolTip="" />
</Window>

Code-behind:

void rtb_ToolTipOpening(object sender, ToolTipEventArgs e)
{
  RichTextBox rtb = sender as RichTextBox;

  if (rtb == null)
    return;

  TextPointer position = rtb.GetPositionFromPoint(Mouse.GetPosition(rtb), false);
  if (position == null)
    return;

  int offset = rtb.Document.ContentStart.GetOffsetToPosition(position);

  position = rtb.Document.ContentStart.GetPositionAtOffset(offset);
  if (position == null)
    return;

  string text = position.GetTextInRun(LogicalDirection.Forward);

  rtb.ToolTip = !string.IsNullOrEmpty(text) ? text.Substring(0, 1) : string.Empty;
}