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;
}
}
}
Beside of that what @mrid mentioned, your singleton implementation might not work quite right. Maybe refer to here on how to make MainWindow
a singleton.
Edit:
As @Tantem mentioned in the comments, the singleton problem can also be easily avoided by calling:
((MainWindow)Application.Current.MainWindow).DrawGrid(rows,cols);