c# - 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;
}
}
}
解决方案
除了@mrid 提到的之外,您的单例实现可能不太正确。也许可以参考这里关于如何制作MainWindow
单例。
编辑:
正如评论中提到的@Tantem,单例问题也可以通过调用来轻松避免:
((MainWindow)Application.Current.MainWindow).DrawGrid(rows,cols);
推荐阅读
- javascript - 在带有锚链接和 jquery 的部分之间跳转
- php - 打破 Else If 语句
- python - 熊猫掉列问题
- mysql - 我如何在 laravel 中编写此连接查询
- spring-boot - 如何使用 Redis Cluster (Elasticache) 修复低生菜客户端性能?
- javascript - nodejs中的语法babel
- google-apps-script - 在新标签页中从脚本打开另一个 google 工作表
- angular - 如何将字符串从 angular 6 发送到 springboot 休息控制器?
- google-tag-manager - 使用 Google 跟踪代码管理器查找和替换页面文本字符串
- kubernetes - Kubernetes etcd 没有出现