2011-05-08 99 views
0

我在WPF窗口上有一个RichTextBox。现在,我想在用户将鼠标移到RichTextBox上时显示一个工具提示。 RichTextBox的内容应该取决于鼠标指针下的文本。为此,我应该得到鼠标显示的字符位置。在RichTextBox上显示工具提示

最好的问候,托马斯

回答

1

在下面的例子中,提示会显示一个字符,其中插入符号。

的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> 

代码隐藏:

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

奔喜。我需要在鼠标光标位置的字符。 – BennoDual 2011-05-09 07:46:41

+0

@ t.kehl对不起,我错过了那部分。无论如何使用[TextPointer](http://msdn.microsoft.com/en-us/library/system.windows.documents.textpointer.aspx)的[GetCharacterRect](http://msdn.microsoft.com/zh-cn/ -us/library/system.windows.documents.textpointer.getcharacterrect.aspx)方法,您可以编写一个函数,该函数采用鼠标位置并查找[包含]的字符(http://msdn.microsoft.com/en-us /library/ms557979.aspx)该位置。我现在正在工作,但是如果你不能找到解决方案,我会尽量在家里以后再做。 – Ben 2011-05-09 08:17:23

+0

嗨,本。我没有这样做:void rtb_ToolTipOpening(object sender,ToolTipEventArgs e){RichTextBox rtb = sender作为RichTextBox; if(rtb == null)return; var position = rtb.GetPositionFromPoint(Mouse.GetPosition(rtb),false); if(position == null)return; var x = rtb.Document.ContentStart.GetOffsetToPosition(position); //我现在可以在位置x }得到文本/字符'mmhh - 我现在不用,我该如何添加这段代码才能读取它:-(你认为,这可行吗? – BennoDual 2011-05-09 14:16:19