0

我有以下代码将Adorners 附加到UIElement我在 a 上的 s 上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;
            }
}

出于某种原因,尽管当我在运行时单击 aRichTextBox时,程序会崩溃,因为asRichTextBox找不到。e.SourceUIElement

selectedElement将只是null

谁能告诉我为什么并请给我一个解决方法?

4

1 回答 1

1

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

但是,您可以通过 FlowDocument 的Parent属性访问 RichTextBox。

if (e.Source is FlowDocument)
{
    selectedElement = ((FlowDocument)e.Source).Parent as UIElement;
}
else
{
    selectedElement = e.Source as UIElement;
}
于 2013-07-22T10:27:03.187 回答