Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
845
How can I get the actual top left location of a dropped TextBlock.
posted

When I drop a TextBlock onto a Canvas I use the following code:

            var canvas = e.DropTarget as Canvas;
            var draggedElement = e.OriginalDragSource;
 
            FrameworkElement newElement = null;
            if (draggedElement is TextBlock)
            {
                var oldText = draggedElement as TextBlock;
                newElement = new TextBlock
                {
                    Text = oldText.Text,
                    TextWrapping = TextWrapping.Wrap,
                    Height = oldText.ActualHeight,
                    Width = oldText.ActualWidth
                };
            }
 
            canvas.Children.Add(newElement);
            Point dropPoint = e.GetPosition(canvas);
            // Need to get point relative to text as well
            newElement.SetValue(Canvas.TopProperty, dropPoint.Y);
            newElement.SetValue(Canvas.LeftProperty, dropPoint.X);

However, the TextBlock is offset as the drop point is the location of the cursor which may be anywhere along the selected text:

    Text Being Dragged

           ^

The same point is returned whether I pass the Canvas or the TextBlock into e.GetPosition.

Parents Reply Children