How to obtain x and y position of element so that a new control placed near it in WPF C# application

I want to show autocomplete box near a focused text box. I have many text box present in the form. All these text boxes are children of a stack panel. So when user clicks in the textbox then autocomplete box should appear below it.

I have created the autocomplete box by adding textblocks to a stack panel. This stack panel has width 150 and height auto. The name of the stack panel is autoCompleteBox.

I want to place this autocomplete box near the focused textbox in the form. To move the autcomplete box below the focused textbox, I am using translate transform.

The problem: I could not able to find out the exact x and y position of the focused textbox.

What I did so far?

Initially I tried to find out its x and y position from screen using below code.

Point pos=targetTextBox.PointToScreen(new Point(0d, 0d));
autoCompleteBox.RenderTransform= new TranslateTransform(pos.X, pos.Y);

But it is not giving desired result.

I also tried below code:

Point pos = targetTextBox.TranslatePoint(new Point(0, 0),this);
autoCompleteBox.RenderTransform= new TranslateTransform(pos.X, pos.Y);

But it is also not giving desired result. (Both case, the autoCompleteBox is placed far from the target textbox)

I want to place the autocomplete box just below the currently focused textbox.

Upvotes: 0

Views: 68

Answers (1)

LadderLogic
LadderLogic

Reputation: 1140

Place your autocomplete box inside a Popup and set the PlacementTarget property to your target text box.

WPF Popup

PlacementTarget property

Upvotes: 1

Related Questions