繁体   English   中英

设置Windows 8 XAML应用程序的UIElement的位置

[英]Setting position of a UIElement for a Windows 8 XAML app

我正在尝试基于像这样的点击/单击来设置图像的位置(注意“ contentGrid”是Page的唯一子元素,并且会填满整个屏幕)

 private void contentGrid_Tapped(object sender, TappedRoutedEventArgs e)
 {
     Uri uri = new Uri("ms-appx:///Images/Test.png");
     BitmapImage bitmap = new BitmapImage(uri);
     Image image = new Image();
     image.Source = bitmap;

     // The .png is a 30px by 30px image
     image.Width = 30;
     image.Height = 30;
     image.Stretch = Stretch.None;

     Point tappedPoint = e.GetPosition(contentGrid);
     TranslateTransform posTransform = new TranslateTransform();
     posTransform.X = tappedPoint.X;
     posTransform.Y = tappedPoint.Y;
     image.RenderTransform = posTransform;
     contentGrid.Children.Add(image);         
 }

结果是单击时,Test.png的图像出现在页面上,但没有出现在我点击/单击的位置。 它在视觉上偏移页面宽度的一半,向下偏移页面高度的一半。

我想在这里了解相对位置-将图片转换为用户实际点击/点击的最佳方式是什么?

在您的情况下使用Grid非常棘手。 使用Canvas而不是Grid

Canvas.SetLeft(image, tappedPoint.X);
Canvas.SetTop(image, tappedPoint.Y);
canvas.Children.Add(image);

尝试设置图像的Margin以显示到鼠标点:

   private void contentGrid_Tapped(object sender, TappedRoutedEventArgs e)
   {
        Uri uri = new Uri("ms-appx:///Images/Test.png");
        BitmapImage bitmap = new BitmapImage(uri);
        Image image = new Image();
        image.Source = bitmap;


        // The .png is a 30px by 30px image
        image.Width = 30;
        image.Height = 30;
        image.Stretch = Stretch.None;

        image.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
        image.VerticalAlignment = System.Windows.VerticalAlignment.Top;
        Point tappedPoint = e.GetPosition(contentGrid);
        contentGrid.Children.Add(image);
        image.Margin = new Thickness(tappedPoint.X, tappedPoint.Y, 0, 0);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM