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:
Labels:
Technology
Subscribe to:
Post Comments (Atom)
9 comments:
This won't work, if you're hosting your element in System.Windows.Forms.Integration.ElementHost.
Window.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:
public 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.
B
Thank you very much for that !!! It's exactly what we need !!!
I forwarded it to my blog and put this link as a reference. Thanks :)
this was really useful! It was exactly what i was looking for.
Thanks..it is really helpful.
good work.
Thanks. It woked
Post a Comment
All comments, questions and other feedback is much appreciated. Thank you!