Home > OS >  C# WPF Call method from a closing window
C# WPF Call method from a closing window

Time:04-14

I have a method in a page public partial class pagThreads : Page for data loading from DB to DataGrid:

public void dbReadData()
{
    DbAccess db = new DbAccess();
    lista = db.GetThreads();
    dgrThreads.ItemsSource = lista;
}

To edit those data I'm opening another window like this (by double clicking on DataGrid row):

private void dgrThreads_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
    wndSabThrEdit wndSabThrEdit = new wndSabThrEdit();
    wndSabThrEdit.ShowDialog();
}

After editing I can save the data by updating the record in DB like this:

public void SaveSettings()
{
    DbAccess dbAccess = new();
    dbAccess.UpdateSabThreads();
    string message = "Settings saved.";
    string title = "Information";
    MessageBoxResult result = System.Windows.MessageBox.Show(message, title, MessageBoxButton.OK, MessageBoxImage.Information);
    if(result == MessageBoxResult.OK)
    {
        Close();    
    }
}

The question is: How to trigger the method dbReadData() again to refresh the data in the the DataGrid, for example after closing the editing window? I will be gratefull for help. Thank you!

CodePudding user response:

From your comment it looks like you think that putting

dbReadData();

after

wndSabThrEdit.ShowDialog(); 

would run immediately.

It won't.

ShowDialog() blocks, and the code will only continue to dbReadData(); after the Window has closed.

So just change to:

private void dgrThreads_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
    wndSabThrEdit wndSabThrEdit = new wndSabThrEdit();
    wndSabThrEdit.ShowDialog();
    SaveSettings();
}

CodePudding user response:

If wndSabThrEdit inherits from Window it has a closing event that you can subscribe to:

wndSabThrEdit.Closing  = (_,_) => dbReadData();
wndSabThrEdit.ShowDialog();
  • Related