Call a wpf form contained in a dll

1

My question is very specific. Let's say I have an assembly c # and I want my assembly interfaces to be xaml. How can I create wpf forms and call them inside the assembly without being inside the executable assembly that mounts a wpf project and that the start is already predefined by app.xaml. Speaking of Form we simply create a form, instantiate it and call it a show. How can I do the same with WPF?

    
asked by Diego Galindo Saeta 27.12.2017 в 11:47
source

1 answer

0

If you mean to show a window of type System.Windows.Window that is contained in a dll, you can achieve it with reflection.

First you have to load the dll that your form using Assembly.LoadFrom() . This method receives the path of the dll and returns an object of type Assembly :

System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom("ruta_dll.dll");

Then you are looking for the class that is type Window using the method Assembly#GetTypes() :

var windowsType = typeof(System.Windows.Window);
assembly.GetTypes().Where(type=> type == windowType);

Since you already have all the class that are of type Window that represents the form, you only need to initialize the instants of the same using the method Activator.CreateInstance() :

var windowInstances = windowsType.Select(x=> Activator.CreateInstance(x) as System.Windows.Window);

Then to show it you would only have to execute the method Window#Show() :

windowInstances.FirstOrDefault()?.Show();

Note that I use FirstOrDefault() since it is understood that in the library you would only have one class that inherits from System.Windows.Window . If you have several, you will have to invent a mechanism to show only the form you want.

Here is the complete code:

var windowsType = typeof(System.Windows.Window);

var windowInstances = System.Reflection.Assembly.LoadFrom("ruta_dll.dll")
                .GetTypes()
                .Where(type=> type == windowType)
                .Select(Activator.CreateInstance);

windowInstances.FirstOrDefault()?.Show();
    
answered by 12.01.2018 / 14:15
source