2
我剛開始使用Silverlight,並決定在Visual Studio 2010中做一個小應用程序。我試圖在Canvas中找到usercontrol的當前位置。這裏是XAML佈局:Silverlight 4 - 我正確使用TransformToVisual()嗎?
<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>
我的用戶控件被添加到「ImageContainer」畫布。 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(新點(0,0)),它總是給我(0,0) ,所以翻譯結果只有5個像素。爲什麼會發生?我沒有正確使用TransformToVisual()嗎?