简体   繁体   English

WPF richTextBox无法识别为UIElement

[英]WPF richTextBox cant identify as UIElement

I have the following code which attaches Adorner s to UIElement s which I have on a Canvas . 我有以下代码将Adorner附加到Canvas上的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;
            }
}

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 . 但是由于某种原因,当我在运行时单击RichTextBox时,程序崩溃了,因为e.Source未将RichTextBox作为UIElement找到。

selectedElement will just be null . selectedElement将只是null

Can anybody tell me why and give me a work around please? 谁能告诉我为什么,请给我个解决办法?

Apparently e.Source is the Document of the RichTextBox that you clicked on. 显然, e.Source是您单击的RichTextBox的Document It is a FlowDocument , which is not derived from UIElement . 它是一个FlowDocument ,不是从UIElement派生的。

You may however access the RichTextBox by the FlowDocument's Parent property. 但是,您可以通过FlowDocument的Parent属性访问RichTextBox。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM