public partial class FooControl : UserControl { public FooControl() { InitializeComponent(); } private void _barButton_Click(object sender, RoutedEventArgs e) { var window = new MyWindow { WindowStartupLocation = WindowStartupLocation.CenterOwner, Owner = Window.GetWindow(this) }; if( window.ShowDialog() == true) { // Ok button clicked, do something useful here... } } }
Comments, how-to's, examples, tools, techniques and other material regarding .NET and related technologies.
Saturday, April 25, 2009
Getting Parent Window for UserControl in WPF
Again a small item that may take you some time to search and find on the internet. Suppose you are working on a WPF based application and you have a UserControl that you want to host inside of a window. In addition you need the window within which the UserControl is hosted.
To find out that parent window you might wonder whether you could use the property 'Parent'. Well that might work in some cases but in other cases it might not. For example the parent might be a Canvas and then it starts to become tricky.
So here is a solution that should make it a bit easier. It uses the static method Window.GetWindow() and passes a reference to the UserControl instance as a parameter:
This won't work, if you're hosting your element in System.Windows.Forms.Integration.ElementHost.
ReplyDeleteWindow.GetWindow(this) returns null and clicking on parent form in task bar will hide your modal dialog confusing the hell out of user.
Any ideas how to find parent's HWND? Then it supposedly a matter of doing
new WindowInteropHelper(window).Owner = hwnd;
... before window.ShowDialog()
Thanks
Just found a way to set an Owner for visuals hosted in ElementHost. Here's my helper function:
ReplyDeletepublic static void SetWindowOwner(Visual visual, Window window)
{
var parent = Window.GetWindow(visual);
if (parent != null)
window.Owner = parent;
else
{
var source = (HwndSource) PresentationSource.FromVisual(visual);
if (source != null)
new WindowInteropHelper(window).Owner = source.Handle;
}
}
Cheers!
thank you. This saved my time and this works for me.
ReplyDeleteB
Thank you very much for that !!! It's exactly what we need !!!
ReplyDeleteI forwarded it to my blog and put this link as a reference. Thanks :)
ReplyDeletethis was really useful! It was exactly what i was looking for.
ReplyDeleteThanks..it is really helpful.
ReplyDeletegood work.
ReplyDeleteThanks. It woked
ReplyDelete