2011-05-08 102 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