【发布时间】:2021-12-30 21:45:25
【问题描述】:
我尝试在 winforms 中使用 MVC 模式,但是当我尝试调用事件时,它始终为空。我将 GameView 表单传递给 Game 类,我将 CityButtonPressed 方法绑定到事件,但是当我运行它时,似乎没有任何绑定。
class Game
{
private readonly IGameView _gameView;
public Game(IGameView view)
{
_gameView = view;
_gameView.CityButtonPressed += CityButtonPressed;
}
public void CityButtonPressed(object sender,EventArgs e)
{
//do something
}
}
public interface IGameView
{
event EventHandler CityButtonPressed;
}
public partial class GameView : Form,IGameView
{
public event EventHandler CityButtonPressed;
public GameView()
{
InitializeComponent();
}
protected virtual void OnButtonPressed(EventArgs e)
{
CityButtonPressed?.Invoke(this, e);
}
private void button1_Click(object sender, EventArgs e)
{
OnButtonPressed(EventArgs.Empty);
}
}
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var gameView = new GameView();
var game = new Game(gameView);
Application.Run(new GameView());
}
}
我做错了什么?
【问题讨论】:
-
@HaraldCoppoolse 在
GameView中的CityButtonPressed事件处理程序 -
这对我来说看起来不太 MVC。您的
Game类看起来像模型和控制器的组合。而且,无论哪种方式,它都不应该知道关于按钮按下的任何事情。 -
您发布的代码没有任何内容表明它不起作用。你能发一个minimal reproducible example吗?
-
您的代码看起来正确。也许
GameView是在事件注册后重新创建的? -
在
GameView的构造函数中下断点,检查是否被多次调用。
标签: c# winforms model-view-controller