The FlyoutCONTROL

http://blogs.msdn.com/b/eternalcoding/archive/2012/07/03/tips-and-tricks-for-c-metro-developers-the-flyout-control.aspx

This article starts a new series about small (but I hope useful) tips that can help you during your development phase.

Today I will talk about how you can create a flyout control.

A flyout control is a popup control you can make appear when you click on a button.

 

I used this control for WorldMonger (a game I currently working on):

The FlyoutCONTROL_第1张图片

The code to create this control is as follows:

 //主要是控制弹出的位置

//UserControl  是popup 里面的资控件 ,

//FrameworkElement  是popup 的地方
public static Popup ShowPopup(FrameworkElement source, UserControl control)
{
    Popup flyout = new Popup();

    var windowBounds = Window.Current.Bounds;
    var rootVisual = Window.Current.Content;

    GeneralTransform gt = source.TransformToVisual(rootVisual);//获得source 相对 rootvisual 的位置

    var absolutePosition = gt.TransformPoint(new Point(0, 0));

    control.Measure(new Size(Double.PositiveInfinity, double.PositiveInfinity));

    flyout.VerticalOffset = absolutePosition.Y  - control.Height - 10;
    flyout.HorizontalOffset = (absolutePosition.X + source.ActualWidth / 2) - control.Width / 2;
    flyout.IsLightDismissEnabled = true;

    flyout.Child = control;
    var transitions = new TransitionCollection();
    transitions.Add(new PopupThemeTransition() { FromHorizontalOffset = 0, FromVerticalOffset = 100 });
    flyout.ChildTransitions = transitions;
    flyout.IsOpen = true;

    return flyout;
}

This helper method just takes a source FrameworkElement (to detect where the flyout must pop up) and a UserControlcontrol to display.

Please note the usage of the PopupThemeTransition to obtain and fluid and cool animation Sourire

在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)。

你可能感兴趣的:(out)