I'm making a snake game in WPF C# and I created a few user controls for different "views", it means I have the MainWindow which inherits from the Window class and several user controls with their xaml files. One user control represents the main menu, another represents option view and so on.
public partial class MainWindow: Window
{
public static Menu menu;
public MainWindow()
{
InitializeComponent();
menu = new Menu();
this.Content = menu;
}
}
like above, in MainWindow I create Menu object (it's a one of the user controls - class and xaml file) and set the content of Window to content of Menu. And then in menu class I do the same, for example like user click on button with text "options", he goes to options user control. I just do
this.Content = new Options(); //"this" is now menu class
when he clicks the button with text "singleplayer", he goes to user control with singleplayer game
this.Content = new Game();
and so on. In this way everything works fine, I can switch between different user controls and "load" different contents to application Window, but every time I create new object and it's the problem. When I go to options and then back to menu, a new object of menu class is creating, I cannot remember the previous settings and etc. I would like to create this only once and then reference to this - load existing object content. I tried using binding but it doesn't work. Ho can I do this? How can I switch between different user controls without data loss and creating new object every time?
You should use singletons.
Singletons allow you to have only one instance of a class. This way, every time you manipulate the instance, you manipulate the same one. This allow you to keep / update the state of the same instance through your code.
It's looking like this, and it's thread safe.
public sealed class YourClass
{
private static readonly YourClass instance = new YourClass();
/* Explicit static constructor to tell C# compiler
* not to mark type as beforefieldinit */
static YourClass()
{
}
private YourClass()
{
}
public static YourClass Instance
{
get
{
return instance;
}
}
}
EDIT: OP's mistake was to set Content of the usercontrol istelf insteand of MainWindow usercontrol. You can get the current window containing usercontrol by using this line of code inside usercontrol.
Window yourParentWindow = Window.GetWindow(this);