• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 5667
  • Last Modified:

Change the location of control at runtime in WPF application.

How to change the location (left and top) of the image control in wpf windows application at runtime?
  • 3
1 Solution
Not very intuitively...  here I've got a form with a button and a textbox both sitting inside a Canvas layout object, I'll use the Click event of the button to change the location of the textbox.  Basically this works by getting the existing X/Y of the textbox, then I'll offset it by a +/- amouhnt in transX/Y.  The values I'm setting are the "attached properties" for it that come from it being inside a Canvas container.

        private void button1_Click(object sender, RoutedEventArgs e)
            int transX = 50;
            int transY = 20;

            GeneralTransform myTrans = this.textBox1.TransformToAncestor(this);
            Point p1 = myTrans.Transform(new Point(0, 0));

            this.textBox1.SetValue(Canvas.LeftProperty, p1.X + transX);
            this.textBox1.SetValue(Canvas.TopProperty, p1.Y + transY);

Mr_JavedAuthor Commented:
Thanks for the reply.

When I created the sample like yours. in VB

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click
        TextBox1.SetValue(Canvas.LeftProperty, 10)
    End Sub

This give me the error : '10' is not a valid value for property 'Left'.
When I changed the value 10 to any other, the same error I'm getting.

What can be the problem?

Mr_JavedAuthor Commented:
That error is solved now. that was because I pass 10, that is integer value and it requires double value.

your solution works. Thanks BitRunner303

Mr_JavedAuthor Commented:
Thanks a lot
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now