28.Sep.15

Vladimir Milev

Vladimir Milev

XAML Goodies - Relative Position Panel (Universal App, WPF, Windows Phone, Silverlight)

Have you ever had the need to position a visual element in a relative fashion in XAML? For example, a special banner that should always sit at 10% from the top of your app, or a golden-ratio guide that should always be positioned correctly no matter how you resize your panel. Have you ever needed a panel which is almost like a Canvas, but instead of absolute units it could use relative ones? If you answered yes to any of the above points you are in for a treat: I've decided to share my implementation of a relative positioning panel. It is very simple to work with it, in a similar fashion to the Canvas with attached properties:

In the above example we are setting the position of the button to be always at 50% height and 50% width of the parent container. The RelativeX and RelativeY properties specify the point at which the control will be positioned. By default the panel centers the child control on top of this point. If you need to control this more precisely you can use the ItemHorizontalPositionAlignment and ItemVerticalPositionAlignment properties to further specify how the control is aligned with respect to the RelativeX/Y point:

The panel code is universal - it will work on WPF, UniversalApps, WindowsPhone, Silverlight. I have included a sample project which demonstrates how to share accommodate the panel source to work with WPF and a UniversalApp. You can find it here on GitHub: https://github.com/vmilev/RelativePositionDemo. Contributions and pull requests are welcome :)

Direct source code link: RelativePositionPanel

Hopefully this will help some of you and as always - Happy Coding!

 

Need consulting on this topic?

Yes No