2013-07-22 33 views
0

我有以下代码,它附加Adorner s到UIElement s,我有一个CanvasWPF richTextBox不能识别为UIElement

private void slideCanvas_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) 
{ 
    { 
       selected = false; 
       if (selectedElement != null) 
       { 
        aLayer.Remove(aLayer.GetAdorners(selectedElement)[0]); 
        selectedElement = null; 
       } 
      } 

      if (e.Source != slideCanvas) 
      { 
       _isDown = true; 
       _startPoint = e.GetPosition(slideCanvas); 

       selectedElement = e.Source as UIElement; 

       _originalLeft = Canvas.GetLeft(selectedElement); 
       _originalTop = Canvas.GetTop(selectedElement); 

       aLayer = AdornerLayer.GetAdornerLayer(selectedElement); 
       aLayer.Add(new ResizingAdorner(selectedElement)); 
       selected = true; 
       e.Handled = true; 
      } 
} 

出于某种原因,尽管当我运行时程序崩溃为RichTextBox中点击一个RichTextBox不受e.Source发现为UIElement

selectedElement只是null

有人可以告诉我为什么,请给我一个工作?

+0

您可以在该行设置一个断点来查看“e.Source”实际是什么。也许它是RichTextBox中的文档元素之一。 – Clemens

+0

e.Source是{System.Windows.Documents.FlowDocument}。我不确定这意味着任何人都可以帮忙吗? – kev3kev3

回答

1

显然e.Source是您点击的RichTextBox的Document。它是一个FlowDocument,它不是从UIElement派生的。

然而,您可能会通过FlowDocument的Parent属性访问RichTextBox。

if (e.Source is FlowDocument) 
{ 
    selectedElement = ((FlowDocument)e.Source).Parent as UIElement; 
} 
else 
{ 
    selectedElement = e.Source as UIElement; 
} 
+0

太棒了,谢谢。现在我可以单击并移动并调整RichTextBox的大小,但实际上我无法输入任何东西。我附加装饰器来调整大小并在Canvas上移动控件。在我可以在RichTextBox中键入任何内容之前,我的previewLeftMouseButtonDown事件是否会触发? – kev3kev3

+0

是的,我想是的。除了通过键盘导航焦点时,使用Tab键。如果您的装饰器用于指示输入焦点,则最好将处理程序附加到[GotFocus](http://msdn.microsoft.com/en-us/library/system.windows.uielement.gotfocus.aspx)和[LostFocus] (http://msdn.microsoft.com/en-us/library/system.windows.uielement.lostfocus.aspx)事件。或Got/LostKeyboardFocus。 – Clemens