0

I have the following code which attaches Adorners to UIElements which I have on a Canvas.

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

For some reason though when I click on a RichTextBox during runtime the program crashes as the RichTextBox is not found by e.Source as UIElement.

selectedElement will just be null.

Can anybody tell me why and give me a work around please?

Dave Clemmer
  • 3,741
  • 12
  • 49
  • 72
kev3kev3
  • 395
  • 1
  • 6
  • 21
  • You may set a breakpoint at that line to see what `e.Source` actually is. Maybe it's one of the document elements inside the RichTextBox. – Clemens Jul 22 '13 at 10:09
  • e.Source is {System.Windows.Documents.FlowDocument}. I'm not really sure what that means can anyone help? – kev3kev3 Jul 22 '13 at 10:18

1 Answers1

1

Apparently e.Source is the Document of the RichTextBox that you clicked on. It is a FlowDocument, which is not derived from UIElement.

You may however access the RichTextBox by the FlowDocument's Parent property.

if (e.Source is FlowDocument)
{
    selectedElement = ((FlowDocument)e.Source).Parent as UIElement;
}
else
{
    selectedElement = e.Source as UIElement;
}
Clemens
  • 123,504
  • 12
  • 155
  • 268
  • Fantastic, thanks. Now I can click and move and resize the RichTextBox but I cant actually type anything in. I am attaching adorners to resize and move controls about on the Canvas. Will it be that my previewLeftMouseButtonDown event is firing before I can type anything in the RichTextBox? – kev3kev3 Jul 22 '13 at 10:37
  • Yes, I guess so. Except when you navigate focus by keyboard, with the Tab key. If your adorner is for indicating input focus, you may better attach handlers to the [GotFocus](http://msdn.microsoft.com/en-us/library/system.windows.uielement.gotfocus.aspx) and [LostFocus](http://msdn.microsoft.com/en-us/library/system.windows.uielement.lostfocus.aspx) events. Or Got/LostKeyboardFocus. – Clemens Jul 22 '13 at 10:46