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();
}
}
Main form:
private void ShowGameOver(string text)
{
var dialog = new GameOverDialog { tb1 = { Text = text } };
dialog.RestartChosenEvent += StartNewGame();
dialog.Show();
}
private void StartNewGame()
{
InitializeComponent();
InitializeGame();
}
After @Fuex's Help*
private void ShowGameOver(string text)
{
var dialog = new GameOverDialog { tb1 = { Text = text } };
dialog.RestartEvent += StartNewGame;
dialog.ExitEvent += Close;
dialog.Show();
}
The 'delegate name is not valid at this point' error can also occur when you're defining a delegate and not using the
new
keyword. For instance:To put this into context you can see the definition of the delegate below. In asp.net if you're defining usercontrol that needs to get a value from its parent page (the page hosting the control) then you'd define your delegate in the usercontrol as follows:
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:Then in your main form you have to use
StartNewGame
, which is the pointer of the method to pass, rather thanStartNewGame()
: