C# Windows Phone应用程序上的矩形用户界面?

C# Windows Phone应用程序上的矩形用户界面?,c#,xaml,windows-phone-8.1,C#,Xaml,Windows Phone 8.1,我有一个xaml页面,我在网格上放了一个矩形(网格覆盖了整个屏幕)。如何获取矩形左上角的坐标 Xaml类: <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

我有一个xaml页面,我在网格上放了一个矩形(网格覆盖了整个屏幕)。如何获取矩形左上角的坐标

Xaml类:

<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>

让我们假设我只是将这个矩形放置在画布上(将其从网格中更改)。如何获得矩形左上角的坐标

谢谢

把它弄明白了

double x = Canvas.GetLeft(TestRectangle);
double y = Canvas.GetTop(TestRectangle);
可以使用将点或矩形从一个UIElement的坐标系转换为另一个UIElement的坐标系

矩形的左上角坐标在矩形坐标中始终为0,0,因此如果将其转换为画布坐标,则可以查看新值以查看矩形的位置

这将适用于任意两个UIElement,因此您可以保留网格,而不必依赖Canvas.Left和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);

也许你应该把矩形放在画布里而不是网格里。。Canvas可以让你根据坐标来定位矩形。你可以发布你的XAML视图的代码吗?我添加了我的XAML代码。好的,我也会试试。