用TransformToVisual和Transform取得元素绝对位置(Location)

来源:互联网 发布:二级域名 端口 编辑:程序博客网 时间:2024/06/06 03:53

在Silverlight的Layout中,控件往往是相对放置,例如Grid/Border/ListBox等,这个时候就是要取得子控件的绝对位置(location)怎么办?使用场景很多,例如,我们点击一个按钮,动画打开一个弹出窗口,关闭那个窗口,能够动画缩小到按钮的位置 - 这样我们就要取得按钮的绝对位置。可以用GeneralTransform.Transform方法来获得,当然首先要用UIElement.TransformToVisual来获得相对于祖宗的位置。代码如下:

   1: GeneralTransform gt = yourUIElment/*控件*/.TransformToVisual(Application.Current.RootVisual as UIElement);
   2: Point offset = gt.Transform(new Point(0, 0));
   3: double controlTop = offset.Y;
   4: double controlLeft = offset.X;

注:如果把上面的Application.Current.RootVisual换成其他元素就可以获得元素相对于其他元素的相对位置(Location)。

 

对了,前提是你要先找到那个元素,可以用FindName方法,或者遍历Silverlight对象树也可以,如果用Template还要用GetTemplateChild。详情见Silverlight对象树MSDN。

转自: http://www.cnblogs.com/Mainz/archive/2011/10/23/2222080.html