How can we create a Singleton Instance for a Window?

放肆的年华 提交于 2020-01-13 13:12:36

问题


I have searched for creating a Singleton object for a window in WPF.

public static Test DefInstance
{
    get
    {
        if (formDefInstance == null)  // formDefInstance.IsDisposed
        {
            initializingDefInstance = true;
            formDefInstance = new cas18();
            initializingDefInstance = false;
        }
        return formDefInstance;
    }
    set { formDefInstance = value; }
}

But the forDefInstance.IsDisposed is not working and throwing an error.

Any Idea regarding this?


回答1:


I think everyone should take a look at Jon Skeet's C# In Depth site. If only to read and permanently burn into their brains the singleton patter a-la C#.

http://csharpindepth.com/Articles/General/Singleton.aspx

In your scenario, try to implement this (thread safe, non-lazy):

public sealed class DefInstance
{
  private static readonly DefInstance instance = new DefInstance();
  static DefInstance()
  {
  }

  private DefInstance()
  {
  }

  public static DefInstance Instance
  {
    get
    {
      return instance;
    }
   }
} 

There are also Lazy<T> implementions and various other implementations of the pattern in that site.




回答2:


I don't know if it's what you want to do but it works for me :

private static MyWindow _defInstance;
public static MyWindow DefInstance
{
    get
    {
        if (null == _defInstance)
        {
            _defInstance = new MyWindow();
        }
        return _defInstance;
    }
 }

In MyWindow code :

protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
    this.Visibility = Visibility.Hidden;
    e.Cancel = true;
}

To use it :

DefInstance.Show();

Then, only one window is display and you use one instance of your window.




回答3:


you can achieve this by implementing following method

private static volatile DefInstance instance;
private static object syncRoot = new Object();

private DefInstance() {}

public static DefInstance Instance
{
   get 
   {
      if (instance == null) 
      {
         lock (syncRoot) 
         {
            if (instance == null) 
               instance = new DefInstance();
         }
      }

      return instance;
   }
}


来源:https://stackoverflow.com/questions/16056161/how-can-we-create-a-singleton-instance-for-a-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!