从 WPF 中删除某些形状

  • 本文关键字:删除 WPF c# 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);
}
}

}

任何帮助将不胜感激。

我不确定我在代码示例中是否拥有所需的一切,但看起来正在创建一个形状并将其添加到列表中,但也分配给一个名为"shape"的成员,该成员被创建的最新形状覆盖。然后,您始终会删除该最新形状。应将鼠标向下处理程序附加到每个形状,从对象发送器捕获形状,并将其从列表中删除。

private void shape_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
Shape s = sender as Shape;
mc.Children.Remove(s);
shapes.Remove(s);
}

我建议您学习 WPF 中的命中测试。看看这个问题,我回答了如何在鼠标下获取几何图形并将其删除。您只需要根据您的任务调整此代码,但这非常简单。

XAML:

<Canvas Mouse.MouseDown="Canvas_MouseDown">

代码隐藏:

private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
var canvas = sender as Canvas;
if (canvas == null)
return;
HitTestResult hitTestResult = VisualTreeHelper.HitTest(canvas, e.GetPosition(canvas));
var shape = hitTestResult.VisualHit as Shape;
if (shape == null)
return;
canvas.Children.Remove(shape);
shapes.Remove(shape); // I think you don't need list of shapes
}

MouseButtonEventArgs.OriginalSource属性返回单击的Shape,以便您可以像这样实现mc_MouseRightButtonDown事件处理程序:

private void mc_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{
Shape clickedShape = e.OriginalSource as Shape;
if (clickedShape != null)
{
mc.Children.Remove(clickedShape);
shapes.Remove(clickedShape);
}
}

最新更新