创建代表事件 [英] Creating Delegate Events
问题描述
我正在尝试创建一个可以以另一种形式访问的委托事件。但主要形式看不到能看到我的代表。它表示委托名称在这一点上无效。
模态表单
I'm trying to create a delegate event that is accessible in another form. But the main form doesn't seen to be able to see my delegate. It say delegate name is not valid at this point. modal form
public partial class GameOverDialog : Window
{
public delegate void ExitChosenEvent();
public delegate void RestartChosenEvent();
public GameOverDialog()
{
InitializeComponent();
}
private void closeAppButton_Click(object sender, RoutedEventArgs e)
{
ExitChosenEvent exitChosen = Close;
exitChosen();
Close();
}
private void newGameButton_Click(object sender, RoutedEventArgs e)
{
RestartChosenEvent restart = Close;
restart();
Close();
}
}
主窗体:
private void ShowGameOver(string text)
{
var dialog = new GameOverDialog { tb1 = { Text = text } };
dialog.RestartChosenEvent += StartNewGame();
dialog.Show();
}
private void StartNewGame()
{
InitializeComponent();
InitializeGame();
}
@ Fuex的帮助之后 / strong>
After @Fuex's Help*
private void ShowGameOver(string text)
{
var dialog = new GameOverDialog { tb1 = { Text = text } };
dialog.RestartEvent += StartNewGame;
dialog.ExitEvent += Close;
dialog.Show();
}
推荐答案
delegate void RestartChosenEvent()
声明允许封装方法的引用类型。所以通过使用它 + = StartNewGame
给出错误。正确的代码是:
It doesn't work because delegate void RestartChosenEvent()
declares the type of the reference which allows to encapsulate the method. So by using on it += StartNewGame
gives an error. The right code is:
public partial class GameOverDialog : Window
{
delegate void myDelegate();
public myDelegate RestartChosenEvent;
public myDelegate ExitChosenEvent;
public GameOverDialog()
{
InitializeComponent();
}
private void closeAppButton_Click(object sender, RoutedEventArgs e)
{
ExitChosenEvent();
this.Close();
}
private void newGameButton_Click(object sender, RoutedEventArgs e)
{
RestartChosenEvent();
this.Close();
}
}
然后在您的主窗体中,您必须使用 StartNewGame
,它是方法传递的指针,而不是 StartNewGame()
:
Then in your main form you have to use StartNewGame
, which is the pointer of the method to pass, rather than StartNewGame()
:
private void ShowGameOver(string text)
{
var dialog = new GameOverDialog { tb1 = { Text = text } };
dialog.RestartChosenEvent += StartNewGame;
dialog.Show();
}
这篇关于创建代表事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!