1

I am trying to draw a rectangle at the point in a canvas where the user clicks. I want my window to be scale- able so I have placed the Canvas in a viewbox but this doesn't draw the rectangle on the specified point but is variable based on the scaling of the viewbox. here is my code

<Viewbox MouseLeftButtonDown="Viewbox_MouseLeftButtonDown" Width="300" Height="300">
    <Canvas Name="Surface" MouseLeftButtonDown="Surface_MouseRightButtonDown" Background="Transparent" Width="300" Height="300"></Canvas>
</Viewbox>

here is the viewbox mouse down event

 private void Viewbox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        Rectangle rect = new Rectangle { Width = 10, Height = 10, Fill = Brushes.Black };
        Surface.Children.Add(rect);
        Canvas.SetLeft(rect, e.GetPosition(this).X);
        Canvas.SetTop(rect, e.GetPosition(this).Y);
    }

The result is the same even if I call the Canvas mouse event.

4

1 回答 1

0

Viewbox 控件没有背景,因此无法接收鼠标事件。我会将画布包装在背景设置为透明的边框中,然后将我的事件处理程序附加到那里。设置 Viewbox 的宽度和高度也没有多大意义,因为您可能希望它随内容缩放。

<Viewbox Width="300" Height="300">
  <Border Background="Transparent"            
          MouseLeftButtonDown="Border_MouseLeftButtonDown"
    <Canvas Name="Surface" Background="Transparent" Width="300" Height="300"/>
  </Border>
</Viewbox>

您的另一个问题是您正在获得相对于this. 我不知道是什么this,但你想获得鼠标相对于画布的位置。

 private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
 {
     var rect = new Rectangle { Width = 10, Height = 10, Fill = Brushes.Black };
     Surface.Children.Add(rect);
     Canvas.SetLeft(rect, e.GetPosition(Surface).X);
     Canvas.SetTop(rect, e.GetPosition(Surface).Y);
 }
于 2016-04-17T18:28:30.810 回答