user5582011
user5582011

Reputation:

C# WPF How to start a function in WindowA by action on WindowB?

I have two Windows: MainWindow and AddAlarm.

AddAlarm is getting opened by a button which is in MainWindow. (MainWindow is still active) When I typed in my data in AddAlarm, I press the "OK" button and AddAlarm get's closed. After pressing "OK" I want to activate a function which is in MainWindow.cs

But how do I do that?

Opens new window (AddAlarm)

private void Button_AddAlarm_Click(object sender, RoutedEventArgs e)
    {

        AddAlarm frm = new AddAlarm(); 
        frm.Show();
        frm.Activate();

    }

Pressing "OK"-button in AddAlarm window

private  void Button_OK_Click(object sender, RoutedEventArgs e)
    {

          // some code which activates function in MainWindow

    }

Function in MainWindow

 public void Refresh()
    {
        string[] refresh = new string[0];

        refresh = File.ReadAllLines("Alarms.txt");
    }

There might be a clever and easy solution, but I just don't know how to do that.

I appreciate your help,

thanks

Upvotes: 0

Views: 48

Answers (2)

j.i.h.
j.i.h.

Reputation: 827

More complicated, but more "idiomatic", would be to rely on callback events (like an AlarmAdded event with an Alarm parameter which would be registered right after the AddAlarm is created and raised by the AddAlarm window when it's done).

The approach I would probably take would be to just open AddAlarm modally--that way you can read the information you need from the AddAlarm window in the same block.

private void Button_AddAlarm_Click(object sender, RoutedEventArgs e)
{
    AddAlarm frm = new AddAlarm(); 
    // ShowDialog waits until AddAlarm is closed before returning
    frm.ShowDialog();
    // Recommended to add a check on frm.DialogResult to verify whether the user OK'd or Cancelled.
    if (frm.DialogResult = DialogResult.Ok) {
        AlarmSettings settings = frm.AlarmSettings;
        Alarm createdAlarm = new Alarm (AlarmSettings);
    }
}

Upvotes: 0

Mihail Shishkov
Mihail Shishkov

Reputation: 15847

This totally depends on you but here is a simple solution.

private void Button_AddAlarm_Click(object sender, RoutedEventArgs e)
    {

        AddAlarm frm = new AddAlarm(this);  // pass a reference to main window 
        frm.Show();
        frm.Activate();

    }

you'll need to create a private MainWindow mainWindow; in AddAlarm window and assign it in the constructor.

Then

private  void Button_OK_Click(object sender, RoutedEventArgs e)
    {

          this.mainWindow.Refresh();

    }

Upvotes: 2

Related Questions