3
votes

I got a WPF project, which is compiled into a dll and will be called from another application. That's how it is set up. In this WPF project I need to pop up a customized message box from the view model of the main window to show messages to the user. This customized message box requires a Window parameter. That's how it is.

For a WPF application, Application.Current.MainWindow will get me what I need. But here it is a dll, so Application.Current is null, and leads to run time exception. I also tried something like Window.GetWindow(this). Here it is not working, because 'this' is the view model, so it won't give me the handle of the main window.

What else can I try to get the handle of the main window here?

Thanks.

1
why do you need main window to popup other messagebox?Nitin
You can get it through Reflection and instansiate it through Activator.CreateInstance()Omri Btian
Can you say a bit more on how to use Reflection to do that?user2417994
How will the view model be created? Somebody must create the main window and the view model and put them together. This is where you can do something. But on the other hand, you do not want the view to be known too much in the view model... The Cinch MVVM framework has a nice way of connecting them in a rather weak way...meilke
@user2417994 I posted an answer with a small example of the use of reflection, but I must say that I still don't entirely understand your need. If all you want to do is show the customized message box that lies in the WPF assembly, in your other application, that can be achieved through reflection and has no need in accessing the WPF application's main window. If you need something else, please elaborate ... I'll update my answer accordingly :)Omri Btian

1 Answers

0
votes

Once you get the application dll, and assuming you know the window's name, you can get and instaniate it through reflection

string myWpfAssemblyPath = ""; // Enter the path to your application here
Assembly wpfAppAssembly = Assembly.Load(myWpfAssemblyPath);

var MainWindow = (Window)wpfAppAssembly.CreateInstance("myMainWindow");

Note that this will create a new instance of the window, and not get you a handle of a window that is already running. to get a window handle that is already instansiated, you could use WIN32 API.

Here are some links to help you do that:

Get Window instance from Window Handle

Get Application's Window Handles

http://social.msdn.microsoft.com/Forums/vstudio/en-US/1d7bd916-9bbe-4c76-b9a0-8306159035a1/faq-item-how-to-retrieve-a-window-handle-in-visual-cnet

Hope this helps