Show ToolTip on RichTextBox

扶醉桌前 提交于 2019-12-04 21:42:45

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!