asp.net中通过委托、事件在子窗口和父窗口间传值

作者:袖梨 2022-06-25

下面这种方法是使用委托事件来实现以上功能:

我们以登录为例,子窗体 AccountWindow :

①定义委托:

 代码如下 复制代码

public delegate void LoginSuccessedDelegate(object sender, LoginSuccessedEventArgs e);
public event LoginSuccessedDelegate LoginSuccessedEvent;

②事件传值:

 代码如下 复制代码

private void LoginButton_Click(object sender, RoutedEventArgs e)
{
this.Close();
LoginSuccessedEventArgs loginAccount = new LoginSuccessedEventArgs();
loginAccount.Account = "123"+DateTime.Now.Second.ToString();
LoginSuccessedEvent(sender,loginAccount);
}
//定义传值数据类型
public class LoginSuccessedEventArgs : EventArgs
{
public string Account{get;set;}
}

父窗体:

①触发登录事件

 代码如下 复制代码

private void Login_Click(object sender, RoutedEventArgs e)
{
AccountWindow accountWindow = new AccountWindow(this);

  //注册事件
accountWindow.LoginSuccessedEvent += new AccountWindow.LoginSuccessedDelegate(accountWindow_LoginSuccessedEvent);
accountWindow.ShowDialog();
}

②登录成功事件返回值处理(这个地方我们可以获取到登录返回值,根据返回值操作父窗体属性和资源,省去了传递父窗体给子窗体)

 代码如下 复制代码

void accountWindow_LoginSuccessedEvent(object sender, AccountWindow.LoginSuccessedEventArgs e)
{
UserInfo.Content ="当前帐号:"+ e.Account;
}

相关文章

精彩推荐