DigitalMath
DigitalMath

Reputation: 85

Rectangle UI on Windows Phone app?

I have a xaml page that I put a rectangle on a grid (grid covers whole screen). How do I go about getting the coordinates of the Rectangle's upper left corner?

Xaml class:

<Page
x:Class="JunkyJunk.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:JunkyJunk"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

<Canvas>
    <Rectangle x:Name="TestRectangle" 
               Fill="#FFF4F4F5"
               HorizontalAlignment="Left"
               Height="100"
               Stroke="Black" 
               VerticalAlignment="Top" 
               Width="100" 
               Loaded="TestRectangle_Loaded" Canvas.Left="137" Canvas.Top="245"/>
</Canvas>

So lets just say I just place this rectangle onto a canvas (changed it from a grid). How would I get the coordinates of the rectangle's upper left corner?

Thanks

Upvotes: 2

Views: 535

Answers (2)

Rob Caplan - MSFT
Rob Caplan - MSFT

Reputation: 21919

You can use a GeneralTransform to convert a point or rectangle from one UIElement's coordinate system to another's.

The rectangle's top left coordinates will always be 0,0 in the rectangle's coordinates, so if you translate that to your canvas' coordinates then you can look at the new value to see where the Rect is.

This will work with any two UIElements, so you could keep your Grid and not have to rely on Canvas.Left and Canvas.Top.

// Rectangle's bounds in its own coordinates
Rect testRectLocalBounds = new Rect(0, 0, TestRectangle.ActualWidth, TestRectangle.ActualHeight);

// Transforms from TestRectangle's to this page's and to TestCanvas' coordinates
GeneralTransform transformToPage = TestRectangle.TransformToVisual(this);
GeneralTransform transformToCanvas = TestRectangle.TransformToVisual(TestCanvas);

// TestRectangle's boundaries in the Page's and Canvas' coordinates
Rect testRectPageBounds = transformToPage.TransformBounds(testRectLocalBounds);
Rect testRectCanvasBounds = transformToCanvas.TransformBounds(testRectLocalBounds);

Debug.WriteLine("Rect relative to page: {0} to canvas: {1}", testRectPageBounds, testRectCanvasBounds);

Upvotes: 0

DigitalMath
DigitalMath

Reputation: 85

Figured it out.

double x = Canvas.GetLeft(TestRectangle);
double y = Canvas.GetTop(TestRectangle);

Upvotes: 2

Related Questions