Sometime we need to reset the position of the Silverlight Child Window at the center of the screen. This generally require when you have a static instance of the ChildWindow and you want to use the same instance to show various messages in the screen. When you loads the ChildWindow for the first time, by default it loads at the screen center. But think when your user reposition that ChildWindow to a different location in the screen, closes and reopens it, what will happen?
What will you see is, the ChildWindow opens at the same location where the user closes it last time. So, how can we reset it to the center of the screen? This small tip will help you to achieve the functionality. Read it to know more details. Code is available for use.
The Silverlight ChildWindow internally implements it’s Template with a Grid named “ContentRoot”. If you edit your ChildWindow Template, you will see the following code:
You will see, it has a Grid named “ContentRoot”, which also has RenderTransform implemented in it. The TransformGroup of the Grid.RenderTransform contains various transformation of the Grid panel like ScaleTransform, SkewTransform, RotateTransform and TranslateTransform.
Here the TranslateTransform is use to position the ChildWindow. If you can set the X and Y coordinates of the TranslateTransform of the ChildWindow, you are done.
In this post, I will show you how to achieve that. To do this, we will create a Extension class for the ChildWindow and will implement the method to center it in the screen.
Let’s have a look into the implemented class here:
We created a static class having a static method “CenterInScreen()” which takes the instance of the ChildWindow as the parameter. From the instance of the ChildWindow, we will get the root which is nothing but a Grid. This Grid consists of another Grid named “ContentRoot”. Once you get the ContentRoot from the ChildWindow template, we can iterate through the TransformGroup to find the TranslateTransform. It is by default present in ChildWindow. Once you get the Translate Transform, change it’s X and Y coordinate values to ‘0’ (zero).
That’s all about it. If you want to position it somewhere else, set them there instead of ‘0’. Remember that, before doing this operation i.e. before calling the CenterInScreen() your Child Window needs to be added in the layout. If you didn’t add the ChildWindow to the layout before calling the method, you will see the “ArgumentOutOfRangeException”:
The extension method will help you to call the CenterInScreen() directly from the ChildWindow instance. Hope this information will help you when you work with the same.