revolutionkpi
revolutionkpi

Reputation: 2682

How get a current position of textBox

How can I get a current position of textBox element when call this method?

 private void UserTextBox_GotFocus(object sender, RoutedEventArgs e)
        {

        }

UPDATE

 GeneralTransform gt = this.TransformToVisual(Application.Current.RootVisual as UIElement);
            Point offset = gt.Transform(new Point(0, 0));
            double controlTop = offset.Y;
            double controlLeft = offset.X;

When I use this controlTop and controlLeft are (0,0)

Upvotes: 1

Views: 2490

Answers (3)

David Jones
David Jones

Reputation: 582

I wanted all of my textboxes to go to the right edge (minus 20). They are all aligned horizontally on the left.

I enabled the page SizeChanged event handler then added:

        private void Page_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            GeneralTransform gt = tbSvcMsgOut.TransformToVisual(this);
            Point offset = gt.TransformPoint(new Point(0, 0));
            double controlTop = offset.Y;
            double controlLeft = offset.X;
            double newWidth =  e.NewSize.Width - controlLeft - 20;
            if (newWidth > tbSvcMsgOut.MinWidth)
            {
                tbSvcMsgOut.Width = newWidth;
                tbDeviceMsgIn.Width = newWidth;
                tbSvcMsgIn.Width = newWidth;
                tbDeiceMsgOut.Width = newWidth;
            }
        }

This works fine for me, :)

Upvotes: 0

Eugene
Eugene

Reputation: 2985

Get a reference for TextBox like so, don't use "this." "this" in this case is a totally different object:

    private void txt1_GotFocus(object sender, RoutedEventArgs e)
    {
        TextBox t = sender as TextBox;
        GeneralTransform gt ...
    }

Upvotes: 1

omerkirk
omerkirk

Reputation: 2527

Because the "this" in your update is the page object. Name your textbox with x:Name="MyTextbox" in your xaml. Then in your focus event handler:

private void UserTextBox_GotFocus(object sender, RoutedEventArgs e)
{
    GeneralTransform gt = MyTextbox.TransformToVisual(Application.Current.RootVisual);
    Point offset = gt.Transform(new Point(0, 0));
    double controlTop = offset.Y;
    double controlLeft = offset.X;
}

In your code you are trying to get absolute position of the page according to the application that is why you are getting 0 for offset values.

Upvotes: 1

Related Questions