我有2个WinForms,其中一个是父级,并将参数传递给它的chilf形式。代码如下:
public class FormMain : Form {
private User user;
public FormMain (User user) {
InitializeComponent();
this.user = user;
}
private void btnUpdateAccount_Click(object sender, EventArgs e)
{
updateUser = new FormUsersUpdate(user);
updateUser.Show();
}
}
和此:
public class FormUsersUpdate(User user){
//Update user in database
}
用户类有一些常用的属性,如姓名,姓氏等。所以我的问题是如何通知父类有关此更新而无需再次从数据库中检索用户?
感谢。
答案 0 :(得分:3)
一些选项:
答案 1 :(得分:3)
您可以在更新后调用回调委托。在FormMain
:
private void btnUpdateAccount_Click(object sender, EventArgs e)
{
updateUser = new FormUsersUpdate(user, new Action<User>(OnUserUpdated));
updateUser.Show();
}
private void OnUserUpdated(User user)
{
// Whatever you wanted to do with the updated user.
}
在FormUsersUpdate
:
public class FormUsersUpdate(User user, Action<User> callback)
{
// Update user, then invoke the callback using the updated user instance,
// which will call the OnUserUpdated method of the FormMain:
callback.Invoke(user);
}
ShowDialog主要是一个更好的选择,但我从来没有在mdi孩子身上尝试过:
private void btnUpdateAccount_Click(object sender, EventArgs e)
{
updateUser = new FormUsersUpdate(user);
updateUser.ShowDialog();
// Will wait until the user closes the dialog box.
// FormUserUpdate keeps the updated user in a property called User:
OnUserUpdated(updateUser.User);
}
答案 2 :(得分:0)
如果您只是想要传递值,那么将它们作为父公共静态变量公开,并在子窗口中设置它们。
父:
public static User CurrentUser {get; set;}
子:
FormMain.CurrentUser = user;
FormMain.CurrentUser.LastName = "Menefee";
答案 3 :(得分:0)
以下是使用委托和事件的上述问题的工作示例:
public partial class FormUsersUpdate : Form
{
private readonly User user;
public delegate void UserChangedEventHandler(object sender, EventArgs e);
public event UserChangedEventHandler UsrChanged;
private void InvokeUsrChanged()
{
var args = new EventArgs();
if (UsrChanged != null) UsrChanged(this, args);
}
public FormUsersUpdate()
{
InitializeComponent();
}
public FormUsersUpdate(User usr)
{
InitializeComponent();
this.user = usr;
this.user.name = "Kishore";
}
private void FormUsersUpdate_Load(object sender, EventArgs e)
{
InvokeUsrChanged();
}
}
公共部分类Form1:表单 { 私人用户; FormUsersUpdate _frmusrUpdate;
public Form1()
{
InitializeComponent();
this.user = new User { name = "Test" };
}
private void button1_Click(object sender, EventArgs e)
{
_frmusrUpdate = new FormUsersUpdate(this.user);
_frmusrUpdate.UsrChanged += new FormUsersUpdate.UserChangedEventHandler(_frmusrUpdate_UsrChanged);
_frmusrUpdate.Show();
}
void _frmusrUpdate_UsrChanged(object sender, EventArgs e)
{
MessageBox.Show("User Details Changed");
}
}