2014-01-29 17 views

回答

0

我想這取決於你什麼時候彈出什麼。 MSDN的一個示例顯示瞭如何在RichTextBox控件中定位ContextMenu以及所選文本的位置。 How to: Position a Custom Context Menu in a RichTextBox 我們感興趣的是下面的代碼:

TextPointer position = rtb.Selection.End; 

if (position == null) return; 

Rect positionRect = position.GetCharacterRect(LogicalDirection.Forward); 
contextMenu.HorizontalOffset = positionRect.X; 
contextMenu.VerticalOffset = positionRect.Y; 

這得到了選擇的相對位置。如果你彈出一個表單,你需要把它翻譯成一個窗口位置。

這是我用來測試加載一個彈出窗口在RichTextBox選定的文本上的一段代碼。這也考慮到了多個監視器。

TextPointer tp = txtEditor.Selection.End; 
if (tp == null) return; 
Rect charRect = tp.GetCharacterRect(LogicalDirection.Forward); 
Point winPoint = txtEditor.PointToScreen(charRect.TopRight); 
Popup p = new Popup(); 
p.Left = winPoint.X; 
p.Top = winPoint.Y; 
p.Show(); 

UPDATE: 我做了一些額外的研究,發現了MSDN Popup Placement Behavior一篇文章,可能你在找什麼,只要Popup行爲。您可以使用上面提供的代碼與RichTextBox的選擇或插入位置,然後確定Popup的最終位置。我希望有所幫助。

0
static void tb_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e) 
    { 


     if (e.KeyStates == ((e.KeyStates^System.Windows.Input.KeyStates.Down)^System.Windows.Input.KeyStates.Down)) 
     { 
      if (e.Key == System.Windows.Input.Key.OemPeriod) 
      { 

       TextBox tb = (TextBox)sender; 

       Rect r = tb.GetRectFromCharacterIndex(tb.CaretIndex, true); 
       Point p = tb.TransformToAncestor(tb).Transform(new Point(r.X, r.Y + 10)); 
       p = tb.PointToScreen(p); 

       Rect rect = new Rect(p.X, p.Y, 0, 0); 
       Grid g = (Grid)Application.Current.MainWindow.Content; 
       System.Windows.Controls.Primitives.Popup popup = new System.Windows.Controls.Primitives.Popup(); 
       popup.SetValue(System.Windows.Controls.Primitives.Popup.PlacementRectangleProperty, rect); 

       popup.IsOpen = true; 
       g.Children.Add(popup);}}} 
+3

你能否提供解答你的答案? – soundslikeodd

相關問題