Search code examples
silverlightpositionchildwindow

How to know the position of the Silverlight ChildWindow when you close it


Please, help me.

public myChildWindow()
{
    InitializeComponent();

    // set left and top from saved values
    Margin = new Thickness(70, 50, 0, 0);
}

private void ChildWindow_Closed(object sender, EventArgs e)
{
    // How to know the position of the ChildWindow when you close it ?
    // get left and top for save values
    ...
}

Solution

  • Oops you are right, try this:

    Wire up the window to the following events (I did this via simple button click)

            var childWindow = new ChildWindow();                        
            childWindow.Closing += new EventHandler<CancelEventArgs>(OnChildWindowClosing);            
            childWindow.Show();
    

    Now what you need to do is walk the ChildWindow PARTS DOM and find the ContentRoot which will give you the position.

        static void OnChildWindowClosing(object sender, CancelEventArgs e)
        {
            var childWindow = (ChildWindow)sender;            
            var chrome = VisualTreeHelper.GetChild(childWindow, 0) as FrameworkElement;
            if (chrome == null) return;
            var contentRoot = chrome.FindName("ContentRoot") as FrameworkElement;
            if (contentRoot == null || Application.Current == null || Application.Current.RootVisual == null) return;
            var gt = contentRoot.TransformToVisual(Application.Current.RootVisual);
            if (gt == null) return;
            var windowPosition = gt.Transform(new Point(0, 0));
            MessageBox.Show("X:" + windowPosition.X + " Y:" + windowPosition.Y);
        }
    

    HTH.