Silverlight Popup Positioning

by zebsadiq 28. January 2011 14:21

Recently I had to convert a few child windows into popup windows. Doing this was pretty easy. I simply changed the child windows into user controls, then added them as child controls of popups at runtime. One of the behavioural difference between the child window and pop up box is that by default, a child window opens in the middle of the Silverlight application whereas the Popup appears in the top left corner. After a bit of google-ing, I did not find an out of the box way to make the pop-ups sit in the centre of my screen. Therefore I formulated a way of doing this via code and some basic maths.

private void btn_Open_Click(object sender, RoutedEventArgs e)
       {
           Popup popup = new Popup();

			// Creates a new instance of a user control which 
			// contains some functionality or content
           var newPopupControlContent = new myUserControl();
           popup.Child = newPopupControlContent;

		   
		   // The size of window to display (you may or may not need this)
           double widthOfDialog = 300;
           double heightOfDialog = 400;
		   
		   // Calculate where to position the box
		   // Center of screen minus half width and height of popup
           double positioningX = (Application.Current.Host.Content.ActualWidth / 2) - (widthOfDialog / 2);
           double positioningY = (Application.Current.Host.Content.ActualHeight / 2) - (heightOfDialog / 2);

		   // Check to see whether the position is on screen
           if (positioningX > 0)
               popup.HorizontalOffset = positioningX;

           if (positioningY > 0)
               popup.VerticalOffset = positioningY;

			// Show the pop up
           popup.IsOpen = true;    
       }

Hope this helps save you time. I would still like to know if there is some trick to get the pop ups in the middle of the screen without writing C#.

Tags: , ,

C# | Silverlight

Comments

Add comment




  Country flag

biuquote
  • Comment
  • Preview
Loading



Calendar

<<  April 2024  >>
MoTuWeThFrSaSu
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345

View posts in large calendar