2014-01-29 22 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

相关问题