Display WPF window by name

Project A contains a WPF window (data entry form) with a panel of the stack of commands that run various reports. A menu is a dynamically created list from a database. What I'm trying to do is launch the corresponding WPF window based on the CommandText associated with the menu selection. Id like to create one function that takes a WPF window name (CommandText) and starts a new instance of the window by name.

I found examples of how to run methods in classes, but didn't seem to find a way that works with a window. I know that this can be done with a switch and just display all the windows, but there are 60-70, and I tried to avoid bloating.

I was unable to retry using TypeOfand Activator.CreateInstance. Suggestions? Is it possible?

+3
source share
2 answers

You can try the following:

string windowClass = "CreateWindow.MyWindow";
Type type = Assembly.GetExecutingAssembly().GetType(windowClass);
ObjectHandle handle = Activator.CreateInstance(null, windowClass);
MethodInfo method = type.GetMethod("Show");
method.Invoke(handle.Unwrap(), null);

The above code assumes that your window is called "CreateWindow.MyWindow" (with a namespace prefix) and that the type "CreateWindow.MyWindow" is in the current executable assembly.

+1
source

Activator works great for me. What is your mistake? Try if below code will work for you

private void Button_Click(object sender, RoutedEventArgs e)
{
    Window wnd = (Window)CreateWindow("WpfApplication1.Window2");
    wnd.Show();

}

public object CreateWindow(string fullClassName)
{
    Assembly asm = this.GetType().Assembly;

    object wnd = asm.CreateInstance(fullClassName);
    if (wnd == null)
    {
        throw new TypeLoadException("Unable to create window: " + fullClassName);
    }
    return wnd;
}
+3
source

Source: https://habr.com/ru/post/1748361/


All Articles