Ilya Verbitskiy

Thoughts and links about computer programming
posts - 16 , comments - 244 , trackbacks - 0

WPF: How to Find Control Location.

Hello everyone! Unfortunately I do not have enough time for blogging this winter. I hope the situation will change pretty soon, and I will find the time to write something here.

Anyway. You know that WPF does UI layout itself and usually you should not specify the exact place for your controls. But sometimes you need to know the exact location of the control. Windows Forms solution is easy: just use Control.Location property which returns you the upper-left corner of the control relative to the upper-left corner of its container. You can achieve the same functionality using Visual.PointToScreen method. It requires one parameter – a Point. The Point is the current coordinates system. It is usually the window’s upper-left corner (0, 0).

 

   1:  element.PointToScreen(new Point(0, 0));

 

Let’s create a simple window with a few buttons. Each button will show it’s screens location when use clicks it. This is our Window.

 

   1:  <WrapPanel>
   2:      <Button>Button 1</Button>
   3:      <Button>Button 2</Button>
   4:      <Button>Button 3</Button>
   5:      <Button>Button 4</Button>
   6:      <Button>Button 5</Button>
   7:      <Button>Button 6</Button>
   8:      <Button>Button 7</Button>
   9:      <Button>Button 8</Button>
  10:      <Button>Button 9</Button>
  11:      <Button>Button 10</Button>
  12:  </WrapPanel>

 

I am using the same UIElement.MouseDown event’s handler for all these buttons. The easiest way to do this is using EventManager.RegisterClassHandler method. It allows you to register a class handler for a particular routed event. This is the code I have added to the Window’s class constructor.

 

   1:  EventManager.RegisterClassHandler(typeof(Button), MouseDownEvent, new RoutedEventHandler(OnMouseDown));

 

The rest of the application is easy: get a button and show its location.

 

   1:  private void OnMouseDown(object sender, RoutedEventArgs e)
   2:  {
   3:      var element = sender as ContentControl;
   4:      if (element != null)
   5:      {
   6:          ShowLocation(element);
   7:      }
   8:  }
   9:   
  10:  private void ShowLocation(ContentControl element)
  11:  {
  12:      var location = element.PointToScreen(new Point(0, 0));
  13:      MessageBox.Show(string.Format(
  14:                                      "{2}'s location is ({0}, {1})", 
  15:                                      location.X, 
  16:                                      location.Y, 
  17:                                      element.Content));
  18:  }

 

And this is it. You may find the example on GitHub.

Print | posted on Tuesday, January 22, 2013 10:37 PM | Filed Under [ WPF ]

Feedback

No comments posted yet.
Post A Comment
Title:
Name:
Email:
Comment:
Verification:
 

Powered by: