2012-08-16 98 views
1

我想從我的鼠標位置向我的網格添加一個橢圓。我如何定義繪製橢圓的位置?將橢圓添加到鼠標位置?

這裏是我的鼠標按下事件:

private void GridCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) 
{ 
    _sensorPoint = Mouse.GetPosition(GridCanvas); 
    AddSensor(); 
} 

而且我AddSensor()方法:

private void AddSensor() 
{ 
    Ellipse sensorEllipse = new Ellipse(); 
    SolidColorBrush solidColorBrush = new SolidColorBrush(); 


    solidColorBrush.Color = Color.FromArgb(0, 0, 0, 0); 
    sensorEllipse.Fill = solidColorBrush; 
    sensorEllipse.StrokeThickness = 2; 
    sensorEllipse.Stroke = Brushes.Black; 
    sensorEllipse.Width = 10; 
    sensorEllipse.Height = 10; 

    GridCanvas.Children.Add(sensorEllipse); 
} 

如何添加sensorEllipse其中點擊畫布上的鼠標?

+0

看看[這個問題](http://stackoverflow.com/questions/6818851/change-stackpanel-location-on-a-canvas-programatically)。 – 2012-08-16 06:47:17

+0

鼠標點的類型是Point,我需要將它們拆分爲兩個雙打,以便與Canvas.SetLeft()一起使用。我需要這樣做嗎? – DommyCastles 2012-08-16 06:50:00

回答

1

可以設置位置與任何這些方法:

private void AddSensor() 
{ 
     Ellipse sensorEllipse = new Ellipse(); 
     SolidColorBrush solidColorBrush = new SolidColorBrush(); 

     solidColorBrush.Color = Color.FromArgb(0, 0, 0, 0); 

     sensorEllipse.Fill = solidColorBrush; 

     sensorEllipse.SetValue(Canvas.LeftProperty, _sensorPoint.X); 
     sensorEllipse.SetValue(Canvas.TopProperty, _sensorPoint.Y); 

     //Canvas.SetLeft(sensorEllipse, _sensorPoint.X); 
     //Canvas.SetTop(sensorEllipse, _sensorPoint.Y); 

     sensorEllipse.StrokeThickness = 2; 
     sensorEllipse.Stroke = Brushes.Black; 
     sensorEllipse.Width = 10; 
     sensorEllipse.Height = 10; 

     //adding event handler for right mouse down: 
     sensorEllipse.MouseRightButtonDown += new MouseButtonEventHandler(sensorEllipse_MouseRightButtonDown); 

     GridCanvas.Children.Add(sensorEllipse); 
} 

EDIT 對於添加/刪除橢圓檢查,該鼠標按鈕在GridCanvas_MouseLeftButtonDown

private void GridCanvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) 
{ 
    _sensorPoint = Mouse.GetPosition(GridCanvas); 
    AddSensor(); 
} 

按下然後加入事件處理程序對於新的橢圓:

void sensorEllipse_MouseRightButtonDown(object sender, MouseButtonEventArgs e) 
    { 
     Ellipse ellipse = sender as Ellipse; 
     GridCanvas.Children.Remove(ellipse); 
    } 
+0

非常感謝! 我將如何去除它們從鼠標位置? – DommyCastles 2012-08-16 07:48:48

+0

當用戶按住鼠標按鈕時是否要添加橢圓,並在釋放鼠標按鈕時將其刪除? – JleruOHeP 2012-08-16 08:26:01

+0

我想在用戶點擊鼠標左鍵(我的代碼時)時添加一個橢圓,並在用戶右擊橢圓時刪除它。 – DommyCastles 2012-08-16 09:33:50