我嘗試了WPF,我希望能夠通過左擊創建形狀,但有正確的單擊右鍵刪除鼠標指針當前盤旋的形狀,但是,會發生什麼反而是創建的最後一個形狀被刪除。我該如何解決?從WPF中刪除某些形狀
這將創建形狀:
private List<Shape> shapes = new List<Shape>();
private Shape shape;
public static Random rand = new Random();
private Rectangle CreateRectangle()
{
int height = rand.Next(0, 151);
int width = rand.Next(0, 101);
byte alpha = (byte)rand.Next(0, 256);
byte alpha2 = (byte)rand.Next(0, 256);
byte alpha3 = (byte)rand.Next(0, 256);
Rectangle rect = new Rectangle();
rect.Width = width;
rect.Height = height;
SolidColorBrush color = new SolidColorBrush();
color.Color = Color.FromRgb(alpha, alpha2, alpha3);
rect.Fill = color;
return rect;
}
private Ellipse CreateEllipse()
{
int height = rand.Next(0, 151);
int width = rand.Next(0, 101);
byte alpha = (byte)rand.Next(0, 256);
byte alpha2 = (byte)rand.Next(0, 256);
byte alpha3 = (byte)rand.Next(0, 256);
Ellipse ellipse = new Ellipse();
ellipse.Width = width;
ellipse.Height = height;
SolidColorBrush color = new SolidColorBrush();
color.Color = Color.FromRgb(alpha, alpha2, alpha3);
ellipse.Fill = color;
return ellipse;
}
private void ColumnDefinition_OnClick(object sender, MouseButtonEventArgs e)
{
Point area = System.Windows.Input.Mouse.GetPosition(mc);
int num = rand.Next(1, 3);
switch (num)
{
case 1:
shape = CreateRectangle();
mc.Children.Add(shape);
shapes.Add(shape);
Canvas.SetLeft(shape, area.X);
Canvas.SetTop(shape, area.Y);
break;
case 2:
shape = CreateEllipse();
mc.Children.Add(shape);
shapes.Add(shape);
Canvas.SetLeft(shape, area.X);
Canvas.SetTop(shape, area.Y);
break;
}
}
private void Clear_Click(object sender, RoutedEventArgs e)
{
mc.Children.Clear();
}
這是什麼應該刪除形狀:
private void mc_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
mc.Children.Remove(shape);
shapes.Remove(shape);
}
}
}
任何幫助是極大的讚賞。