2013-04-22 213 views
2

我有繪製橢圓,線條和矩形的簡單應用程序。鼠標在畫布上單擊對象

代碼:

private void Canvas_MouseDown(object sender, MouseButtonEventArgs e) 
    { 
     startPoint = e.GetPosition(canvas); 

     if(figura == "linia") 
     { 
      linia = new Line 
      { 
       Stroke = Brushes.LightBlue, 
       StrokeThickness = 2 
      }; 

      canvas.Children.Add(linia); 
     } 

     if (figura == "kwadrat") 
     { 
      rect = new Rectangle 
      { 
       Stroke = Brushes.LightBlue, 
       StrokeThickness = 2 
      }; 

      Canvas.SetLeft(rect, startPoint.X); 
      Canvas.SetTop(rect, startPoint.X); 

      canvas.Children.Add(rect); 
     } 

     else if (figura == "kolko") 
     { 
      circ = new Ellipse 
      { 
       Stroke = Brushes.LightBlue, 
       StrokeThickness = 2 
      }; 

      Canvas.SetLeft(circ, startPoint.X); 
      Canvas.SetTop(circ, startPoint.X); 

      canvas.Children.Add(circ); 
     } 
    } 

    private void Canvas_MouseMove(object sender, MouseEventArgs e) 
    { 
     if (e.LeftButton == MouseButtonState.Released || rect == null && circ == null && linia == null) 
      return; 

     var pos = e.GetPosition(canvas); 

     var x = Math.Min(pos.X, startPoint.X); 
     var y = Math.Min(pos.Y, startPoint.Y); 

     var w = Math.Max(pos.X, startPoint.X) - x; 
     var h = Math.Max(pos.Y, startPoint.Y) - y; 

     if(figura == "linia") 
     { 
      linia.X1 = startPoint.X; 
      linia.Y1 = startPoint.Y; 
      linia.X2 = pos.X; 
      linia.Y2 = pos.Y; 
     } 

     if (figura == "kwadrat") 
     { 
      rect.Width = w; 
      rect.Height = h; 

      Canvas.SetLeft(rect, x); 
      Canvas.SetTop(rect, y); 
     } 

     if (figura == "kolko") 
     { 
      circ.Width = w; 
      circ.Height = h; 

      Canvas.SetLeft(circ, x); 
      Canvas.SetTop(circ, y); 
     } 
    } 
    private void Canvas_MouseUp(object sender, MouseButtonEventArgs e) 
    { 
     rect = null; 
     circ = null; 
    } 

現在我想做的事情與像大小調整對象的東西,移動等等。當他們被鼠標單擊。我不知道如何找到被鼠標點擊的對象。你可以幫我嗎 ?

+1

在你自己做所有事情之前。考慮使用[Thumb](http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.thumb.aspx)控件,該控件完美適用於調整大小和移動對象。除此之外,爲什麼畫布需要了解這些項目?你應該檢查Panel和ItemsControl是什麼。 – dowhilefor 2013-04-22 16:04:37

+0

閱讀此:http://msdn.microsoft.com/en-us/library/ms752097.aspx – mlemay 2013-04-22 16:05:08

回答

2

e.OriginalSource會讓你得到實際點擊的控件。

+0

其實OriginalSource會給你複雜的控件或用戶控件中的原始元素。例如,如果您單擊一個按鈕,則OriginalSource可能是Border元素或ButtonChrome元素,但Source始終是Button本身。 – 2013-04-22 16:12:59

+0

很好,當我點擊對象時,一些動作完成了,但是如果。如果我嘗試改變X1的行是點擊:e.OriginalSource.X1 = 50;這是一個錯誤。 – Finchsize 2013-04-22 17:54:33

+2

@Finchsize你忘了施放它嗎?該屬性返回一個對象。 – 2013-04-22 18:00:13

2

使用RoutedEvent.Source屬性。

if (e.Source is Rectangle) 
{ 
} 
else if (e.Source is Ellipse) 
{ 
} 
else if (e.Source is Line) 
{ 
} 
相關問題