首页 > 解决方案 > Trying to call a function from another form, but it won't work

问题描述

So I'm quite new to programming and especially c# so i hope you can help me. I have two WPF forms and when I'm pressing a button in one of them I want to draw a grid in my canvas. So when I click the button it calls the right function and everything, but the grid just won't show up. I tried to look up people with similar problems but couldn't figure out what is wrong. Here is some of my code:

namespace GameOfLife
{
  public partial class SetupPopUp : Window
  {
    public SetupPopUp()
    {
      InitializeComponent();
    }

    private void OkButton_Click(object sender, RoutedEventArgs e)
    {
      int cols;
      int rows;

      int.TryParse(tb_numCol.Text, out cols);
      int.TryParse(tb_numRows.Text, out rows);
      this.Close();
      MainWindow.Instance.DrawGrid(rows,cols);
    }
  }
}

and:

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

    private static MainWindow _instance;

    public static MainWindow Instance
    {
      get
      {
        return _instance = _instance ?? new MainWindow();
      }
    }

    public void DrawGrid(int rows, int cols)
    {
      for (int i = 0; i < rows; i++)
      {
        for (int j = 0; j < cols; j++)
        {
          Rectangle r = new Rectangle();                  // Erstellt die Rechtecke und fügt Sie dem Canvas hinzu
          r.Width =  MainCanvas.Width / rows;
          r.Height = MainCanvas.Height / cols;
          r.Fill = Brushes.WhiteSmoke;
          r.Stroke = Brushes.Black;
          r.StrokeThickness = 0.5;
          MainCanvas.Children.Add(r);

          Canvas.SetLeft(r, j * r.Width);                 //Reit die Rechtecke aneinander
          Canvas.SetTop(r, i * r.Height);

          r.MouseDown += R_MouseDown;
        }
      }
    }

标签: c#conways-game-of-life

解决方案


除了@mrid 提到的之外,您的单例实现可能不太正确。也许可以参考这里关于如何制作MainWindow单例。

编辑:

正如评论中提到的@Tantem,单例问题也可以通过调用来轻松避免:

((MainWindow)Application.Current.MainWindow).DrawGrid(rows,cols);

推荐阅读