如何在 XAML 中定位元素(形状)?

How to locate elements (Shapes) in XAML?

   private void DrawView_Tapped(object sender, TappedRoutedEventArgs e)
    {
        DrawView.ReorderMode = ListViewReorderMode.Enabled;
     var Location=   e.GetPosition(null);
     Node MyNode = new Node ();
     MyNode.Position.TranslateX = Location.X;
     MyNode.Position.TranslateY = Location.Y;

     GridPainter.Children.Add(MyNode.Circle);

} //Event that i am trying to use ,GridPainter is jut a Grid

public class Node
{
   public SolidColorBrush SelectedColor { get; set; }
   public Ellipse Circle { get; set; }
    public float XPosition { get; set; }
    public float YPosition { get; set; }
    public CompositeTransform Position { get; set; }
    public Node()
    {
        SelectedColor = new SolidColorBrush(Colors.Red);
        Circle = new Ellipse {Fill=SelectedColor,Width=30,Height=30 };
        Position = new CompositeTransform();
        Circle.RenderTransform = Position;
    }

}//The class that i am using

我想做的是在用户点击屏幕的地方画一个椭圆,但由于某种原因我的方法不起作用。我错过了什么?这在 C# 代码中甚至可能吗?这是我的XAML代码

<Page
x:Class="Graph_Painter.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Graph_Painter"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

<Grid x:Name="GridPainter" 
      Tapped="DrawVi`enter code here`ew_Tapped"
       IsTapEnabled="True" >

</Grid>

CanvasShapes 的更好容器。另外,如果只是需要修改视觉形状的LeftTop考虑使用TranslateTransform作为视觉形状的RenderTransform属性。

您可以根据您的解决方案调整上述代码。

部分XAML(形状容器):

<Canvas x:Name="Canvas1"  Tapped="Canvas_Tapped" Background="White"/>

隐藏代码(Canvas 被点击的事件处理程序):

private void Canvas_Tapped(object sender, TappedRoutedEventArgs e)
{
    var point = e.GetPosition(Canvas1);

    //example shape
    const double width = 30d;
    const double height = 30d;

    var ellipse = new Ellipse
    {
        Width = width,
        Height = height,
        Fill = new SolidColorBrush(Colors.Red),
        RenderTransform = new TranslateTransform
        {
            X = point.X - width/2,
            Y = point.Y - height/2
        }
    };

    Canvas1.Children.Add(ellipse);
}

希望对您有所帮助。