我刚刚开始使用Silverlight,我决定在Visual Studio 2010中做一个小应用程序。我试图在Canvas中找到usercontrol的当前位置。这是XAML布局:
<Grid x:Name="LayoutRoot" Background="#FF141313">
<Grid.RowDefinitions>
<RowDefinition Height="39"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Button Opacity="0.5" Background="{x:Null}" BorderThickness="1" FontFamily="Courier New" Content="Align Images" Cursor="Hand" Name="buttonAlignImages" Click="buttonAlignImages_Click" Margin="45,8,0,11" HorizontalAlignment="Left" Width="84" />
<Button HorizontalAlignment="Left" Width="33" Opacity="0.5" Background="{x:Null}" BorderThickness="1" FontFamily="Courier New" Content="Home" Cursor="Hand" Margin="8,8,0,11"/>
<Canvas x:Name="ImageContainer" Margin="8" Grid.Row="1" Background="Black"/>
</Grid>
我的usercontrol被添加到“ImageContainer”Canvas中。 XAML中的一个按钮称为“buttonAlignImages”。当用户点击它时,我基本上希望图像以特定方式对齐。无论如何,我想首先获得嵌入在“ImageContainer”中的usercontrol的位置。所以这是单击按钮时的代码:
private void buttonAlignImages_Click(object sender, RoutedEventArgs e)
{
double margin = 5.0;
Point top_left = new Point(margin, margin);
Point top_right = new Point(ActualWidth - margin, margin);
Point bottom_left = new Point(5.0, ActualHeight - margin);
Point bottom_right = new Point(ActualWidth - margin, ActualHeight - margin);
foreach (UIElement element in ImageContainer.Children)
{
Photo singlePhoto = element as Photo;
if (singlePhoto != null)
{
// get the transform for the current photo as applicable to basically this visual
GeneralTransform gt = singlePhoto.TransformToVisual(ImageContainer);
// get the position on the root visual by applying the transform to the singlePhoto
Point singlePhotoTopLeft = gt.Transform(new Point(0, 0));
// now translate the position of the singlePhoto
singlePhoto.Translate(singlePhotoTopLeft.X - top_left.X, singlePhotoTopLeft.Y - top_left.Y);
}
}
}
public void Translate(double deltaX, double deltaY)
{
translateTransform.X += deltaX;
translateTransform.Y += deltaY;
}
嵌入式照片用户控件确实移动但是当我调用gt.Transform(新的Point(0,0))时它总是给我(0,0),因此得到的转换只有5个像素。为什么会这样?我没有正确使用TransformToVisual()吗?
答案 0 :(得分:0)
已经有一段时间了,但如果没有答案你就无法继续生活:)你会尝试
Point singlePhotoTopLeft = gt.Transform(new Point());
相反?