Reputation: 696
Suppose I have 3 classes to handle all database related requests:
public class DB_A{}
public class DB_B{}
public class DB_C{}
and I got 2 windows to interact with user:
window1.xaml;window1.xaml.cs;
window2.xaml;window2.xaml.cs
as window1 & window2 need to interact with database, they need to use functions from previous 3 classes, I created a class DataHandler:
public class DataHandler
{
public DB_A a;
public DB_B b;
public DB_C c;
public DataHandler()
{
a = new DB_A();
b = new DB_B();
c = new DB_C();
}
//some functions... ...
}
now the class DataHandler can handle all database related request, and now i need to pass a instant of DataHandler to both window1 and window2.
I tried to re-write the constructor for both window1 and window2 with parameter, but it does not allow me to do that. After google i know that WPF window form does not allow constructor with parameter.
Is there any way to pass my DataHandler to the two window form classes?
Upvotes: 1
Views: 2537
Reputation: 699
Yes, you can, there are multiple ways to do that,
Upvotes: 1
Reputation: 361582
Make DataHandler
a singleton, and let the window classes access it.
public class DataHandler
{
//singleton instance
static DataHandler _instance = new DataHandler ();
public DataHandler Instance
{
get { return _instance; }
}
};
Then,
public partial class Window1 : Window
{
DataHandler _dataHandler;
public Window1()
{
InitializeComponent();
_dataHandler = DataHandler.Instance;
}
}
Similarly, write other Window class.
Or even better is, apply some variant of MVP pattern, most likely, MVVM. Read these articles:
Upvotes: 1
Reputation: 96770
There are any number of ways to accomplish this.
You can make DataHandler
a singleton.
Since DataHandler
has a parameterless constructor, you can create it in the application's resource dictionary, and let objects use FindResource
to get it.
One pattern that you'll see pretty commonly, in implementations using the MVVM pattern, is that the view models contain a reference to shared objects, and windows get access to them through binding, though I doubt very much that you're using MVVM.
Upvotes: 0
Reputation: 15413
You can have parameters on your Window constructor. Alternatively you could pass it in through a property, set your DataHandler object to a public static property somewhere, or even just make your DataHandler a static class.
Upvotes: 0
Reputation: 770
Can't you make the DataHandler class to singleton and use it's methods on wherever you want, without re-instantiating the class?
Upvotes: 0