Lot of usercontrols like popup windows, custom-built tooltip windoes, detail-descriptive
windows are launched from our code using the
Show or ShowDialog methods.
But most of the times we incorrectly determine the parent of the such a window. And
moreover, we can't position them aptly.
The following code shows how to use the helper class to do all these.
Popupdialog is the Popup window. The MovewindowIntoBoundsOfScreen moves
the Popup dialog and sets the location of the popup aptly.
private
void PopupDialog_Loaded(object sender, RoutedEventArgs e)
{
WindowHelper.MoveWindowIntoBoundsOfScreen(this);
//
//
}
//Toset the owner property use the GetOwnerWindow method of the helper class.
newPopupDialog
.Owner = WindowHelper.GetOwnerWindow(panel1);
CODE:
using System;
using System.Windows;
using System.Windows.Media;
namespace Helpers
{
/// <summary>
/// Window Helper class.
/// </summary>
public class WindowHelper
{
/// <summary>
/// Gets the owner window.
/// </summary>
/// <param name="dependencyObject">The dependency object.</param>
/// <returns></returns>
public static Window GetOwnerWindow(DependencyObject dependencyObject)
{
DependencyObject
parent = dependencyObject;
DependencyObject
nextParent = parent;
while (nextParent !=
null && !(nextParent
is Window))
{
parent
= LogicalTreeHelper.GetParent(nextParent);
if (parent ==
null && nextParent
is Visual)
{
parent
= VisualTreeHelper.GetParent(nextParent);
}
nextParent
= parent;
}
Window
w = parent
as Window;
if (w !=
null)
{
return w;
}
return Application.Current.MainWindow;
}
/// <summary>
/// Moves the window into bounds of screen.
/// </summary>
/// <param name="window">The window.</param>
public static void MoveWindowIntoBoundsOfScreen(Window window)
{
Rect
screenDimensions = SystemParameters.WorkArea;
if (window.ActualWidth > (screenDimensions.Right - screenDimensions.Left))
{
window.Width
= screenDimensions.Right - screenDimensions.Left;
}
if (window.ActualHeight > (screenDimensions.Bottom - screenDimensions.Top))
{
window.Height
= screenDimensions.Bottom - screenDimensions.Top;
}
if (!
double.IsNaN(screenDimensions.Left) && screenDimensions.Left > window.Left)
{
window.Left
= screenDimensions.Left;
}
else if (!
double.IsNaN(screenDimensions.Right) && screenDimensions.Right < (window.Left
+ window.ActualWidth))
{
window.Left
= screenDimensions.Right - window.ActualWidth;
}
if (!
double.IsNaN(screenDimensions.Top) && screenDimensions.Top > window.Top)
{
window.Top
= screenDimensions.Top;
}
else if (!
double.IsNaN(screenDimensions.Bottom) && screenDimensions.Bottom < (window.Top
+ window.ActualHeight))
{
window.Top
= screenDimensions.Bottom - window.ActualHeight;
}
}
}
}