Wednesday, October 6, 2010

Translating UIElement's position with respect to other UIElement

In this post, we will discuss how we can determine the position of one UIElement with respect to other element.

Let's create a view which has two button. When we click first button, the position of 2nd button (with respect to first element) is displayed in a text block.

<Window x:Class="WPFTranslate_Distance.Window1"
Title="Window1" Height="300" Width="472">
<RowDefinition Height="71*" />
<RowDefinition Height="56*" />
<RowDefinition Height="135*" />
<ColumnDefinition Width="89*" />
<ColumnDefinition Width="80*" />
<ColumnDefinition Width="109*" />
<Button Margin="14,21,14,20" Name="button1" Click="button1_Click">Button 1</Button>
<Button Grid.Column="2" Grid.Row="2" Margin="22,41,22,59" Name="button2">Button 2</Button>
<TextBlock Grid.Column="2" Margin="5,24,13,15" Name="textBlock1" />

The click event of button1 is as follows:

private void button1_Click(object sender, RoutedEventArgs e)
Point p = this.button2.TranslatePoint(new Point(0, 0), this.button1);
this.textBlock1.Text = string.Format("X: {0}, Y: {1}", p.X, p.Y);

Here we are calculating the position of Top Left of Button2 with relative to Button1. When we run the application, the view appears as follows:

As we click Button 1, the position of 2nd button with respect to first button is as follows:

No comments: