Search code examples
c#wpf

Easier opening of Windows with one Void


I have a Launcher for my Software I'm trying to develop. Now the settings have a "Persistent Window" so the launcher does stay open or not after selecting one of it's buttons.

Now I want to simplify the window generation process with on private void in the same class. But I don't know how I give the void the needed window

this is the Project-Structure:

enter image description here

I've tried it with several Types of arguments for the call like "string, Window or type" but every time I'm getting:

"xxx is a variable but it used as Type"

This is the button-code which calls the future window

        private void Btn_NewAdress_Click(object sender, RoutedEventArgs e)
        {
             fun_openWindow(Adress.frm_Adress,"new");
        }

And this is the new void I created:

        private void fun_openWindow(Window selectedWindow, string type)
        {
            selectedWindow form = new selectedWindow();
            form.Show();

            switch (type)
            {
                case "search":
                    form.ti_search.IsSelected = true;
                    break;
                default:
                    form.ti_new.IsSelected = true;
                    break;
            }

            if (Properties.Settings.Default.persistentWindow == true)
            {
                this.Close();
            }
        }

I want that the window I write into the argument will open and if the settings are set, the launcher should close or not.


Solution

  • You can use generic for it:

    private void Btn_NewAdress_Click(object sender, RoutedEventArgs e)
    {
        fun_openWindow<Adress.frm_Adress>("new");
    }
    private void fun_openWindow<YourWindow>(string type) where YourWindow: Window, new()
    {
        YourWindow form = new YourWindow();
        form.Show();
    }
    

    Another way is to use reflection:

    private void Btn_NewAdress_Click(object sender, RoutedEventArgs e)
    {
        fun_openWindow(typeof(Adress.frm_Adress), "new");
    }
    private void fun_openWindow(Type frmType, string type)
    {
        var form = Activator.CreateInstance(frmType) as Window;
        form.Show();
    }