.NET Framework Bookmark and Share   
 index > Windows Presentation Foundation (WPF) > XAML/C# Singleton class?
 

XAML/C# Singleton class?

What is the best way to implement a singleton pattern in XAML/C#? Haven't gotten this to run correctly... I guess it's the way the XAML and C# are tied together...?
DiamonDogX

XAML shouldn't really get in the way here.

<Object xmlns="clr-namespace:System;assembly=mscorlib" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Class="Singleton" />

 

using System;

public partial class Singleton
{
    private static Singleton instance;

    private Singleton()
    {
        InitializeComponent();
    }

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
}
Douglas Stockwell

here is a brief instruction set for how to build a singleton xaml app from scratch.

Then you have to make your own modifications in your app.

follow the steps below

1. Run Visual Studio

2.From the menu Select File -> New Project ->Windows Application (WPF) then OK

3.Double click Window1.xaml.cs

4.Overwritethe partial class Window1 with the code below

public partial class Window1 : System.Windows.Window

{

private static Window1 instance;

private Window1()

{

InitializeComponent();

}

private void InitializeComponent()

{

throw new Exception("The method or operation is not implemented.");

}

public static Window1 Instance

{

get

{

if (instance == null)

{

instance = new Window1();

}

return instance;

}

}

}

5. Double click Window1.xaml

6.Overwrite the first line with the code below

<Window x:Class="WindowsApplication1.Instance"

7.From the menuSelect Debug -> Start Debugging F5

a.ilatzis

XAML shouldn't really get in the way here.

<Object xmlns="clr-namespace:System;assembly=mscorlib" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Class="Singleton" />

 

using System;

public partial class Singleton
{
    private static Singleton instance;

    private Singleton()
    {
        InitializeComponent();
    }

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    }
}
Douglas Stockwell

What if I want my window to be a singleton?

<Window x:Class="???">

DiamonDogX

You just need toreplace the XAML in my example above with:

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="Singleton" />

Douglas Stockwell

My code originally was:

<Window x:Class="UserControlTest.MainWindow"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Title="TITLE"

Height="662"

Width="1105"

ResizeMode="CanResizeWithGrip"

SnapsToDevicePixels="True">

Did what you said... set x:class to "Singleton"... I have errors such as "InitializeComponent" does not exist in the current context.

DiamonDogX

The class name specified by x:Class should alwaysmatch the name of the class in your codebehind file. In my example the class defined by the XAML and the codebehind were called Singleton.

I'm not really sure where you are going wrong. As I said, you don't need to do anything with the XAML to make itconform to thesingleton pattern, just the codebehind - and eventhere it's just as you would do with any other C# class.

Douglas Stockwell

I'm not understanding something I guess... here's my original code:

C#:

namespace UserControlTest

{

/// <summary>

/// Interaction logic for MainWindow.xaml. This window contains a canvas that other user

/// controls can be added to.

/// </summary>

public partial class MainWindow : Window

{

.........

}

XAML:

<Window x:Class="UserControlTest.MainWindow"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Title="TITLE"

Height="662"

Width="1105"

ResizeMode="CanResizeWithGrip"

SnapsToDevicePixels="True">

DiamonDogX

C#:

namespace UserControlTest

{

/// <summary>

/// Interaction logic for MainWindow.xaml. This window contains a canvas that other user

/// controls can be added to.

/// </summary>

public partial class MainWindow : Window

{

private static MainWindow instance;

private MainWindow ()

{

}

private void InitializeComponent()

{

throw new Exception("The method or operation is not implemented.");

}

public static MainWindow Instance

{

get

{

if (instance == null)

{

instance = new MainWindow();

}

return instance;

}

}

}

XAML:

<Window x:Class="UserControlTest.Instance"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Title="TITLE"

Height="662"

Width="1105"

ResizeMode="CanResizeWithGrip"

SnapsToDevicePixels="True">

a.ilatzis

I now get:

Error9'UserControlTest.MainWindow' does not contain a definition for 'mainCanvas'C:\Documents and Settings\daszybr\Desktop\MDIApp\MDIUserControl.xaml.cs40244MDIApp

Error10The name 'InitializeComponent' does not exist in the current contextC:\Documents and Settings\daszybr\Desktop\MDIApp\MainWindow.xaml.cs6413MDIApp

.....

and several more errors on all the components of MainWindow...

I also tried

<Window x:Class="UserControlTest.MainWindow.Instance"....

.......

but then I get "Error8The namespace 'UserControlTest' already contains a definition for 'MainWindow'C:\Documents and Settings\daszybr\Desktop\MDIApp\MainWindow.xaml.cs2426MDIApp
"

DiamonDogX

here is a brief instruction set for how to build a singleton xaml app from scratch.

Then you have to make your own modifications in your app.

follow the steps below

1. Run Visual Studio

2.From the menu Select File -> New Project ->Windows Application (WPF) then OK

3.Double click Window1.xaml.cs

4.Overwritethe partial class Window1 with the code below

public partial class Window1 : System.Windows.Window

{

private static Window1 instance;

private Window1()

{

InitializeComponent();

}

private void InitializeComponent()

{

throw new Exception("The method or operation is not implemented.");

}

public static Window1 Instance

{

get

{

if (instance == null)

{

instance = new Window1();

}

return instance;

}

}

}

5. Double click Window1.xaml

6.Overwrite the first line with the code below

<Window x:Class="WindowsApplication1.Instance"

7.From the menuSelect Debug -> Start Debugging F5

a.ilatzis
Works except on step 6, I had to make it:

<Window x:Class="WindowsApplication1.Window1"....

Thanks.

DiamonDogX

Hello, I fallowed the same method you mentioned here. However, when I try to show the form after it has closed,I am getting "Cannot set Visibility or call Show or ShowDialog after window has closed.". In this sense error message is quite explainatory. Nevertheless I need a single instance child form which can be opened and closed as much as user needs. Please help meabout this matter.

Thanx,

wavewizard
Sounds like you need to abort the close and hide the Window instead. Handle the Closing event on Window and set Cancel on CancelEventArgs to true.
Douglas Stockwell
private void childForm_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
this.Hide();
}
a.ilatzis
dotnetukguru
Hi guys,

This is just a design question.

My application will only have one window. No more windows will be open. Instead there will be lots of user controls being used on the main window.
Should i create a Singleton class for the main window?
Or should i use it on the user controls?

Or do you sugest any other approach?

Cheers
Marco Rosas

You can use google to search for other answers

Custom Search

More Threads

• HierarchicalDataTemplate not finding correct public Type
• Hyperlink in XBAP keeping app in foreground
• Listview column header style
• Getting Started with WPF.
• Binding ValidationRule mechanism
• Cannot load resource from an assembly in XBAP
• HwndSource + task bar + show top + no focus.
• Adding a User control in main Page
• How can I change a style setter using code?
• TwoWay databinding and value Coerce problems (perhaps a bug?)