The following method uses a delegate event to implement the above functions:
Take logon as an example. The subform AccountWindow:
① Define delegation:
| The code is as follows: |
Copy code |
|
Public delegate void LoginSuccessedDelegate (object sender, LoginSuccessedEventArgs e );
Public event LoginSuccessedDelegate LoginSuccessedEvent; |
② Event pass value:
| The code is as follows: |
Copy code |
|
Private void LoginButton_Click (object sender, RoutedEventArgs e)
{
This. Close ();
LoginSuccessedEventArgs loginAccount = new LoginSuccessedEventArgs ();
LoginAccount. Account = "123" + DateTime. Now. Second. ToString ();
LoginSuccessedEvent (sender, loginAccount );
}
// Define the data type of the passed value
Public class LoginSuccessedEventArgs: EventArgs
{
Public string Account {get; set ;}
} |
Parent form:
① Trigger a logon event
| The code is as follows: |
Copy code |
|
Private void Login_Click (object sender, RoutedEventArgs e)
{
AccountWindow accountWindow = new AccountWindow (this );
// Register an event
AccountWindow. LoginSuccessedEvent + = new AccountWindow. LoginSuccessedDelegate (accountWindow_LoginSuccessedEvent );
AccountWindow. ShowDialog ();
} |
② Handle the return value of a successful logon event (in this case, we can obtain the return value for logon and operate the attributes and resources of the parent form based on the return value, saving the need to pass the parent form to the child form)
| The code is as follows: |
Copy code |
|
Void accountWindow_LoginSuccessedEvent (object sender, AccountWindow. LoginSuccessedEventArgs e)
{
UserInfo. Content = "current Account:" + e. Account;
} |