0

In a WPF application, I'd like to create a textbox dynamically which will show in front of the application and be able to freely set its location by pixel. (The textbox is going to follow the mouse cursor).

This was easily done in Winforms on the fly but WPF makes things.. a little bit weird when it comes to setting a control's location by pixel since I have to add the control as a child of a container. I'm aware this is certainly doable on Canvas, but what I actually have is a dockpanel with a richtextbox to the left and a datagrid to the right.

So what are my options here? Do I have to use canvas? Can I get away with using dockpanel (or grid) to implement what I want here?

1 Answer 1

2

You can use a Canvas or a Grid. If you use a Canvas, set the Canvas.Left property and the Canvas.Top property. If you use a Grid, you'll need to set a size for your TextBox, set the HorizontalAlignment to Left, and VerticalAlignment to Top. To change the location of the TextBox, assign it values for MarginLeft and MarginTop.

Sign up to request clarification or add additional context in comments.

2 Comments

Wouldn't grid restrict the location settings of the Textbox as it needs to be bound to a row or a column? (I need the textbox to literally follow the mousecursor anywhere inside the application)
Not assigning the textbox to a row or column in the grid will default it to the first row and column in the top left. The MarginLeft and MarginTop properties will position the textbox relative to this location which happens to be the exact same behavior as if you were to use a Canvas and set Canvas.Left, and Canvas.Top.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.