0

Is there a way to make UserControl a singleton?

ex:
I have a MainWindow and 2 UserControls {UserControl 'A' and UserControl 'B'}
MainWindow have 2 Buttons {Button 'UCA' and Button 'UCB'}
UserControl 'A' have a TextBox.
At startup I have UserControl 'A' loaded to MainWindow.
When I click Button 'UCB', UserControl 'B' will replace UserControl 'A' and when I click Button 'UCA', UserControl 'A' will replace UserControl 'B'.

My question is:
When UserControl 'A' is activated, I type "Test" on TextBox, then I switched to UserControl 'B'. I want when I switched back to UserControl 'A' the text on TextBox is still there. My solution is to create singleton UserControl but I don't know how to do that.

NB: Above is just simple example, what I want to achieve is more complicated than just maintain a text in TextBox when switched between UserControl. But, the point is how to call the same instance of UserControl without created a new one.

1 Answer 1

0

Instead, you should have both user controls loaded in your MainWindow, and toggle their visibility when the buttons are pressed. For instance, if your UserControls are named A and B in Xaml, you'd do the following in codebehind for the UCB.Click handler:

B.Visibility = Visibility.Visible;
A.Visibility = Visibility.Collapsed;

and the opposite for the UCA.Click handler.

Sign up to request clarification or add additional context in comments.

1 Comment

well, I forgot to mention I use a transition animation when changing UserControl. So, the code is much like : transiotion.Content = UserControl; when switched UserControl.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.