2013-10-15 38 views
1

我想在用戶單擊的畫布上的點繪製矩形。我希望我的窗口可縮放,因此我已將Canvas放置在視圖框中,但這不會在指定點上繪製矩形,而是基於視框的縮放而變化。 這裏是我的代碼在wpf中的viewbox上單擊點繪製形狀

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

這裏是視框中鼠標按下事件

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); 
    } 

結果是,即使我打電話畫布鼠標事件一樣。

回答

0

Viewbox控件沒有背景,因此無法接收鼠標事件。我會將Canvas封裝在背景設置爲透明的邊框中,並在其中附加我的事件處理程序。設置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); 
}