【问题标题】:Setting position of a UIElement for a Windows 8 XAML app为 Windows 8 XAML 应用设置 UIElement 的位置
【发布时间】:2012-12-02 21:39:50
【问题描述】:

我正在尝试基于这样的点击/单击设置图像的位置(注意“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的图像在点击时出现在页面上,但不在我点击/点击的位置。它在视觉上偏移了页面宽度的一半,并向下偏移了页面高度的一半。

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

【问题讨论】:

    标签: c# xaml windows-runtime transform uielement


    【解决方案1】:

    尝试将图片的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);
        }
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-21
        相关资源
        最近更新 更多