Tamas555
Tamas555

Reputation: 47

How to pass data from Window to MainWindow in WPF?

Im newbie to programming and now i have a problem with my new login window. I created a new window for login to my server database,but in my mainwindow how do i call it? I don't know how to draw it up better.

In my login window:

using MyS_Database;
MyServer_Database server;

public void LoginButton_Click(object sender, RoutedEventArgs e)
{
    server = new MyServer_Database("ClientName","ServerIP","","",UserID.Text,UserPassword.Password.ToString(),"01",MyServer_Database.LoginType.User,out serverresult)
    swith(serverresult)
    {
    case 0:
    Mainwindow.Show();
    this.Close();
    break;

    default:
    Environment.Exit(0);
    }
}

But when I call a method on my MainWindow which is communicating with the server i have to call it like:

server.GetDataFromUserList();

But It doesn't recognize server,I tried something like Win1.server or similars but I failed. How could i pass it? Thank you in advance!

Upvotes: 1

Views: 297

Answers (1)

Emad
Emad

Reputation: 3949

The quick answer is to make server public like this:

public MyServer_Database Server { get; set; }

Then you can call it in MainWindow with:

Win1.Server.GetDataFromUserList();

But this is not a good approach. Better approach is to abstract away these kind of operations in different classes via MVVM. Read more about MVVM and you'll find great approaches.

Edit

You should also do one one of these two things:

  1. Don't close Win1 instead do this.Hide();

  2. Keep the instance of MyServer_Database in MainWindow by passing it to the constructor of Win1.

You should put this in MainWindow

public MyServer_Database Server { get; set; }

and When needed call this:

var Win1 = new LoginWindow(Server);

Then you have access to Server object in MainWindow

Upvotes: 1

Related Questions