c# 如何擦除 wpf 中绘制的线条

c# How to erase drawn lines in wpf

此 WPF 应用程序有 4 个输入,您可以在其中设置两个点的 x、y 值并绘制一条黑线。问题是......我无法在绘制它们后摆脱这些线条,因此当我想创建新线条时重新启动应用程序是荒谬的。 这是我拥有的:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    Line objLine;
    private void button_Click(object sender, RoutedEventArgs e)
    {
        string tb1 = textBox.Text;
        string tb2 =  textBox1.Text;
        string tb3 = textBox3.Text;
        string tb4 = textBox4.Text;

        double tb1int = double.Parse(tb1);
        double tb2int = double.Parse(tb2);
        double tb3int = double.Parse(tb3);
        double tb4int = double.Parse(tb4);

        Line objLine = new Line(); //point input

        objLine.Stroke = System.Windows.Media.Brushes.Black;
        objLine.Fill = System.Windows.Media.Brushes.Black;

        objLine.X1 = tb1int;
        objLine.Y1 = tb2int;


        objLine.X2 = tb3int;
        objLine.Y2 = tb4int;

        hello.Children.Add(objLine);
}

 private void button2_Click(object sender, RoutedEventArgs e)
    {

        if (objLine != null)
        {
            hello.Children.Remove(objLine);
        }
    }

为什么不像 Children.Remove(line) 那样直接删除它呢?也许您的问题是 Line 对象是方法的局部对象,您可以将其设为全局变量并保存对它的引用,这样您就可以随时删除该行。

Line objLine;

private void button_Click(object sender, RoutedEventArgs e)
{
    objLine = new Line(); //point input
    ...
    hello.Children.Add(objLine);
}

private void removeButton_Click(object sender, RoutedEventArgs e)
{
    if(objLine != null) {
       hello.Children.Remove(objLine);
    }
}

我相信您已经尝试从 hello 容器中删除 line 元素(我自己做的第一件事 :))但没有任何反应。

您可能需要做的是 invalidate 您的 UI。您需要重新绘制或刷新 UI 才能动态更改内容。

您可以使用 UIElement.InvalidateVisual 方法。

或者如果它不起作用,您可能需要传递一个 empty delegate 来刷新您的 UI。请参阅 this article 了解如何操作。 本质上,你会做这样的事情:

public static class ExtensionMethods
{
  private static Action EmptyDelegate = delegate() { };

  public static void Refresh(this UIElement uiElement)
  {
    uiElement.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate);
  }
}

然后在您的容器上调用 hello.Refresh()。当然在删除 line 元素之后。