Add Singleton UserControl in WPF
-
Hi again! I created an UserControl which is a singleton.
public partial class DeepDisplay : UserControl
{
private static DeepDisplay instance;
private static object lockObject = new object();private DeepDisplay() { InitializeComponent(); } public static DeepDisplay GetInstance() { lock (lockObject) { if (instance == null) instance = new DeepDisplay(); } return instance; } }
What I want to do is to add this UserControl in the XAML Part of the code.
<local:DeepDisplay x:Name="deepDisplay" Width="Auto"></local:DeepDisplay>
Due to the fact that the Constructor is private, I need to call the GetInstance Method instead. Can this be done easily and if so, can someone be so kind a show me how? As always thank you in advance, eza
-
Hi again! I created an UserControl which is a singleton.
public partial class DeepDisplay : UserControl
{
private static DeepDisplay instance;
private static object lockObject = new object();private DeepDisplay() { InitializeComponent(); } public static DeepDisplay GetInstance() { lock (lockObject) { if (instance == null) instance = new DeepDisplay(); } return instance; } }
What I want to do is to add this UserControl in the XAML Part of the code.
<local:DeepDisplay x:Name="deepDisplay" Width="Auto"></local:DeepDisplay>
Due to the fact that the Constructor is private, I need to call the GetInstance Method instead. Can this be done easily and if so, can someone be so kind a show me how? As always thank you in advance, eza
I'm quite sure that is impossible. Anyway, a singleton control sounds like a very bad idea. First of all why would you need such a thing? Seccondly, how would you expect it to work when you add a seccond "instance" of the control? I'm asking this because a control can only have one parent, so it can't be in to places at once. On the other side, if you want to make sure that the control is only used once, you could keep track of the number of instances created in a static variable, and throw an error when another instance has already been created. Mihai,