Ant*_*yrd 3 c# wpf delegates modal-dialog
我正在尝试创建一个可以以另一种形式访问的委托事件。但主窗体看不到我的代表。它说此时代表名称无效。情态形式
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();
}
}
Run Code Online (Sandbox Code Playgroud)
主要形式:
private void ShowGameOver(string text)
{
var dialog = new GameOverDialog { tb1 = { Text = text } };
dialog.RestartChosenEvent += StartNewGame();
dialog.Show();
}
private void StartNewGame()
{
InitializeComponent();
InitializeGame();
}
Run Code Online (Sandbox Code Playgroud)
在 @Fuex 的帮助后*
private void ShowGameOver(string text)
{
var dialog = new GameOverDialog { tb1 = { Text = text } };
dialog.RestartEvent += StartNewGame;
dialog.ExitEvent += Close;
dialog.Show();
}
Run Code Online (Sandbox Code Playgroud)
它不起作用,因为delegate void RestartChosenEvent()
声明了允许封装方法的引用类型。所以通过使用它+= StartNewGame
会产生错误。正确的代码是:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
然后在主窗体中,您必须使用StartNewGame
,它是要传递的方法的指针,而不是StartNewGame()
:
private void ShowGameOver(string text)
{
var dialog = new GameOverDialog { tb1 = { Text = text } };
dialog.RestartChosenEvent += StartNewGame;
dialog.Show();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3791 次 |
最近记录: |