Reputation: 2715
My main window has spawned a child window that's positioned on top to look like part of the main. I would like to move the child window in sync with the main but I'm not sure how.
My main window has my own title bar which event MouseLeftButtonDown calls this function:
public void DragWindow(object sender, MouseButtonEventArgs args)
{
DragMove();
UpdateChildWindowPosition();
}
This results in DragMove() executing on the main window moves the main window alone as I drag the title bar. UpdateChildWindowPosition() is not executed until I release the mouse at which it reads some element coordinates and sets the child window position - you see the child window snap to the location which is not desired.
How can I have the child window move in sync with the main window?
Upvotes: 7
Views: 5256
Reputation: 2535
Here is what I did:
I first set an Instance of the Parent as the owner of the Child window, (make an instance by setting it in the MainWindow class public static MainWindow instance;
then instance = this;
) :
public ChildWindow()
{
Owner = MainWindow.instance;
InitializeComponent();
}
Then I add an event handler in the Parent Class to fire when the Parent is moving:
public MainWindow()
{
InitializeComponent();
LocationChanged += new EventHandler(Window_LocationChanged);
}
Now I loop through all the windows owened by the MainWindow to reset their margin:
private void Window_LocationChanged(object sender, EventArgs e)
{
foreach (Window win in this.OwnedWindows)
{
win.Top = this.Top + ((this.ActualHeight - win.ActualHeight) / 2);
win.Left = this.Left + ((this.ActualWidth - win.ActualWidth) / 2);
}
}
Upvotes: 1
Reputation: 2715
AH HAH!
My Main window has an event LocationChanged which I've tied to my UpdateChildWindowPosition(). LocationChange fires when (duh) the location changes so it's continuously firing as I move the window when DragMove() is being executed in my DragWindow posted above.
Upvotes: 5
Reputation: 28699
Can you expose a DragMove() method for the "child" form? Then just call it from the parent?
public void DragWindow(object sender, MouseButtonEventArgs args)
{
DragMove();
UpdatePosition();
childForm.DragMove();
childForm.UpdatePosition();
}
or if you are just using the mouse position to determine where to move the form, do the same calculations in your current DragMove() method and change the Form.Location property of your child form also?
Upvotes: 0
Reputation: 966
You can use the window's Left and Top properties to place the secondary window. Here's a rough bit of code as an example:
In the MainWindow code:
mDebugWindow.Left = this.Left + this.ActualWidth;
mDebugWindow.Top = this.Top;
In this case mDebugWindow is my child window. This code tells it to sit on the right hand side of the main window, with the tops of the windows aligned.
Hope this helps.
Upvotes: 4