Silverlight をいじり始めたばかりで、Visual Studio 2010 で小さなアプリを作成することにしました。キャンバス内のユーザー コントロールの現在の位置を見つけようとしています。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>
私のユーザーコントロールは「ImageContainer」キャンバスに追加されます。XAML のボタンの 1 つは、"buttonAlignImages" と呼ばれます。ユーザーがこれをクリックすると、基本的に画像を特定の方法で整列させたいと思います。とにかくこれを行うには、最初に「ImageContainer」に埋め込まれたユーザーコントロールの位置を取得したいと思います。ボタンがクリックされたときのコードは次のとおりです。
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(new Point(0,0)) を呼び出すと、常に (0,0) が返されるため、結果の変換は 5 ピクセルだけになります。なぜこれが起こるのですか?TransformToVisual() を正しく使用していませんか?