简体   繁体   中英

how to call method from another window in WPF

I have two windows win1 for display a list of Users and the other win2 for adding user.

I also have a method to refresh the grid after deleted or updated or added user. This method is in win1 .

How do I call this method from win2 after add user?

This is a pretty basic Object Oriented Design question. So you want to be able to call back from win2 to a function in win1 after a user is added on win2 . Well, does win2 have a reference to the win1 object? If so, then that's how you call it. If not, then you need to give it one (passing it in to the constructor or something).

Alternatively, if you're using an MVVM framework, you could go down the route of using a Messenger. Most of the MVVM frameworks have one included and they're very useful. I recommend going that route unless this is some sort of throwaway program where the plumbing wouldn't be worth it.

If you are opening Window 2 from Window 1, you could do something like:

// code in Window1
public void AddNewUser()
{
    Window2 window = new Window2();
    if (window.ShowDialog() == true)
    {
        // Update DataGrid
        RefreshDataGrid();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM