16 Mayıs 2010 Pazar

Determine ChildWindow Position At Runtime

  private FrameworkElement root;
private FrameworkElement contentroot;
private FrameworkElement chrome;

private Point childWindowOffset;


 



public MyChildWindow()
{
InitializeComponent();
Loaded
+= new RoutedEventHandler(ThisChildWindow_Loaded);
}


 



In the RoutedEventHandler ThisChildWindow_Loaded we get access with VisualTreeHelper on the VisualTree of the control template and doing so we assign to our three variables root, contentroot and chrome the corresponding element parts of the control template. To the MouseButtonEventHandler of the chrome we add a further MouseLeftButtonUpEvent called Chrome_MouseLeftButtonUp using AddHandler, in which we later add our code to determine the position.



private void ThisChildWindow_Loaded  (object sender, RoutedEventArgs e )
{
if (VisualTreeHelper.GetChildrenCount(this) == 0)
{
Dispatcher.BeginInvoke(()
=> ThisChildWindow_Loaded(this, e));
return;
}
root
= (FrameworkElement)VisualTreeHelper.GetChild(this, 0);
contentroot
= root.FindName("ContentRoot") as FrameworkElement;
chrome
= root.FindName("Chrome") as FrameworkElement;
if (chrome != null)
{
chrome.AddHandler(MouseLeftButtonUpEvent,
new MouseButtonEventHandler(Chrome_MouseLeftButtonUp), true);
}
}


 



Then we must build our routine Chrome_MouseLeftButtonUp where we will call the function GetChildWindowOffset. The actual calculation of the new location takes place in the function GetChildWindowOffset. Here is the code for GetChildWindowOffset:



private void Chrome_MouseLeftButtonUp
(
object sender,
MouseButtonEventArgs e
)
{
this.childWindowOffset =
GetChildWindowOffset
(
e.GetPosition(root),
e.GetPosition(contentroot)
);
}


 



To calculate the new position in the function GetChildWindowOffset the values of X and Y of ContentRootMousePosition is subtracted from the value of X and Y value of RootMousePosition respectively:



  result.X = RootMousePosition.X - ContentrootMousePosition.X;
result.Y = RootMousePosition.Y - ContentrootMousePosition.Y;



 



reference: http://blogs.windowsclient.net/silverlaw/archive/2010/04/15/how-to-determine-new-childwindow-position-at-runtime-silverlight-3.aspx

Hiç yorum yok:

Yorum Gönder