在对另一个窗口执行某些操作后更新wpf父窗口
本文关键字:窗口 更新 wpf 操作 另一个 执行 | 更新日期: 2023-09-27 18:29:40
我有一个名为usermanagement的wpf窗口,有一个显示所有用户的列表框,我在usermanagement窗口中有一个按钮,名为adduser,当我点击打开的名为adduser的新窗口时,这个窗口中有添加新用户的输入字段,当我保存数据时我需要什么,这个adduser窗口关闭,然后usermanagement窗口更新列表框,意味着用户再次更新(新添加的用户应在添加后显示)。现在我需要再次打开usermanagement窗口来查看新添加的用户。谢谢
这是下面的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections;
using Model;
namespace Views
{
/// <summary>
/// Interaction logic for frmUserManagement.xaml
/// </summary>
public partial class frmUserManagement : Window
{
public frmUserManagement()
{
InitializeComponent();
}
public void window_loaded(object sender, RoutedEventArgs e)
{
load_users();
}
public void load_users()
{
RST_DBDataContext conn = new RST_DBDataContext();
var users = (from s in conn.TblUsers
select s.UserName).ToList();
Login_Names.ItemsSource = users;
}
private void add_user(object sender, RoutedEventArgs e)
{
adduser AddUserWindow = new adduser();
AddUserWindow.ShowDialog();
}
}
}
在xaml文件中有
<Grid>
<ListBox Name="Login_Names" HorizontalAlignment="Left" Height="337" Margin="10,47,0,0" Padding="0,0,0,0" VerticalAlignment="Top" Width="156">
<Button Content="Add" HorizontalAlignment="Left" Margin="10,404,0,0" VerticalAlignment="Top" Width="75" Click="add_user"/>
</Grid>
在主窗口(UserManagmentWindow)内执行插入操作:
UserManagmentWindow.cs:
// Inside add button handler open adduser window as dialog box...
var result = adduser.ShowDialog();
if(result == true){
// user pressed OK button...
// insert new user in database
// refresh UserManagmentWindow
}
如果您需要更多详细信息,请发布您的代码。。。
您可以在AddUser窗口中声明一个事件,并在按下按钮时触发该事件。
首先定义EventArgs子类
public class AddUserEventArgs : EventArgs
{
public User AddInfo { get; private set; }
public AddUserEventArgs(User info)
{
this.AddInfo = info;
}
}
在AddUser类中:
public event EventHandler<AddUserEventArgs> AddedUser;
private void Button_Click(Object sender, RoutedEventArgs)
{
User info = new User();
// Realize your validation here...
// If validation is Okay, then..
if (OK)
{
if (this.AddedUser != null)
this.AddedUser(this, new AddUserEventArgs(info));
this.Close();
}
}
在用户管理类中:
var window = new AddUserWindow();
window.AddedUser += (sender, e) =>
{
// Add the info to your ObservableCollection.
this.collection.Add(e.AddInfo);
}
window.ShowDialog();