Question

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?

Was it helpful?

Solution

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top