Iyas
Iyas

Reputation: 520

Open Form Using Singleton and Passing Parameter

I have this class (taken from the net):

class SingletonFormProvider
{
    static Dictionary<Type, Form> mTypeFormLookup = new Dictionary<Type, Form>();

    static public T GetInstance<T>(Form owner)
        where T : Form
    {
        return GetInstance<T>(owner, null);
    }

    static public T GetInstance<T>(Form owner, params object[] args)
        where T : Form
    {
        if (!mTypeFormLookup.ContainsKey(typeof(T)))
        {
            Form f = (Form)Activator.CreateInstance(typeof(T), args);
            mTypeFormLookup.Add(typeof(T), f);
            f.Owner = owner;
            f.FormClosed += new FormClosedEventHandler(remover);
        }
        return (T)mTypeFormLookup[typeof(T)];
    }

    static void remover(object sender, FormClosedEventArgs e)
    {
        Form f = sender as Form;
        if (f == null) return;

        f.FormClosed -= new FormClosedEventHandler(remover);
        mTypeFormLookup.Remove(f.GetType());
    }
}

If using standard open, I know how to pass parameter:

        Form f = new NewForm(parameter);
        f.Show();

But I'm using this way of opening new form (with the help of the above class):

        var f = SingletonFormProvider.GetInstance<NewForm>(this);
        f.Show();

So, how can I pass parameter with this way of opening new form?

Please help.

Thanks.

Upvotes: 0

Views: 574

Answers (2)

mlorbetske
mlorbetske

Reputation: 5659

The GetInstance<T> method has a params object[] parameter at the end. It essentially says that you can keep giving it arguments and they'll be put into an object[] for you.

That method, when it calls Activator.CreateInstance, hands off those parameters to the constructor of your form.

Unfortunately, though, your parameters will only be passed to that child form at the first time it is created, not each time the form is shown as the forms being created are cached versus their types. If you need to set some values on your child form when it is displayed, I'd recommend creating an Initialize method on that form that accepts the parameters you need to set.

Example

public class NewForm : Form
{
    ...

    public NewForm(string constructorMessage)
    {
        //Shows the message "Constructing!!!" once and only once, this method will 
        //never be called again by GetInstance
        MessageBox.Show(constructorMessage);
    }

    public void Initialize(string message)
    {
        //Shows the message box every time, with whatever values you provide
        MessageBox.Show(message);
    }
}

Calling it like this

var f = SingletonInstanceProvider.GetInstance<NewForm>(this, "Constructing!!!");
f.Initialize("Hi there!");
f.Show();

Upvotes: 1

mit
mit

Reputation: 1841

Please refer A Generic Singleton Form Provider for C#. You may get help from this.

Upvotes: 0

Related Questions