Show ToolTip on RichTextBox

白昼怎懂夜的黑 提交于 2019-12-06 15:07:44

问题


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;
}


来源:https://stackoverflow.com/questions/5928809/show-tooltip-on-richtextbox

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