Universal Windows Platform – Wrap Control

Wrap Control demonstrates how to create a Wrap Panel Control

Step 1

If not already, follow Setup and Start on how to Install and get Started with Visual Studio 2017 or in Windows 10 choose Start, and then from the Start Menu find and select Visual Studio 2017.

vs2017

Step 2

Once Visual Studio Community 2017 has started, from the Menu choose File, then New then Project…

vs2017-file-new-project

Step 3

From New Project choose Visual C# from Installed, Templates then choose Blank App (Universal Windows) and then type in the Name as WrapControl and select a Location and then select Ok to create the Project
vs2017-new-project-wrap-control

Step 4

Then in New Universal Windows Project you need to select the Target Version this should be at least the Windows 10 Fall Creators Update (10.0; Build 16299) and the Minimum Version to be the same.

vs2017-target-platform

The Target Version will control what features your application can use in Windows 10 so by picking the most recent version you’ll be able to take advantage of those features. To make sure you always have the most recent version, in Visual Studio 2017 select Tools Extensions and Updates… then and then see if there are any Updates

Step 5

Once done select from the Menu, Project, then Add New Item…

vs2017-project-add-new-item

Step 6

From the Add New Item window select Visual C#, then Code from Installed then select Code File from the list, then type in the Name as WrapPanel.cs before selecting Add to add the file to the Project

vs2017-add-new-item-wrap-control

Step 7

Once in the Code View for WrapPanel.cs the following should be entered:

// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.

using System;
using System.Runtime.InteropServices;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace WrapControl
{
    public partial class WrapPanel : Panel
    {
        [StructLayout(LayoutKind.Sequential)]
        internal struct OrientedSize
        {
            private Orientation orientation;
            private double direct;
            private double indirect;

            public Orientation Orientation
            {
                get { return orientation; }
            }

            public double Direct
            {
                get { return direct; }
                set { direct = value; }
            }

            public double Indirect
            {
                get { return indirect; }
                set { indirect = value; }
            }

            public double Width
            {
                get
                {
                    return (Orientation == Orientation.Horizontal) ? Direct : Indirect;
                }
                set
                {
                    if (Orientation == Orientation.Horizontal)
                    {
                        Direct = value;
                    }
                    else
                    {
                        Indirect = value;
                    }
                }
            }

            public double Height
            {
                get
                {
                    return (Orientation != Orientation.Horizontal) ? Direct : Indirect;
                }
                set
                {
                    if (Orientation != Orientation.Horizontal)
                    {
                        Direct = value;
                    }
                    else
                    {
                        Indirect = value;
                    }
                }
            }

            public OrientedSize(Orientation orientation)
                : this(orientation, 0.0, 0.0)
            {

            }

            public OrientedSize(Orientation orientation, double width, double height)
            {
                this.orientation = orientation;
                direct = 0.0;
                indirect = 0.0;
                this.Width = width;
                this.Height = height;
            }
        }

        private bool ignorePropertyChange;

        public static bool AreClose(double left, double right)
        {
            if (left == right)
            {
                return true;
            }
            double a = (Math.Abs(left) + Math.Abs(right) + 10.0) * 2.2204460492503131E-16;
            double b = left - right;
            return (-a < b) && (a > b);
        }

        public static bool IsGreaterThan(double left, double right)
        {
            return (left > right) && !AreClose(left, right);
        }

        public double ItemHeight
        {
            get { return (double)GetValue(ItemHeightProperty); }
            set { SetValue(ItemHeightProperty, value); }
        }

        public static readonly DependencyProperty ItemHeightProperty =
            DependencyProperty.Register("ItemHeight", typeof(double), typeof(WrapPanel),
                new PropertyMetadata(double.NaN, OnItemHeightOrWidthPropertyChanged));

        public double ItemWidth
        {
            get { return (double)GetValue(ItemWidthProperty); }
            set { SetValue(ItemWidthProperty, value); }
        }

        public static readonly DependencyProperty ItemWidthProperty =
            DependencyProperty.Register("ItemWidth", typeof(double), typeof(WrapPanel),
                new PropertyMetadata(double.NaN, OnItemHeightOrWidthPropertyChanged));

        public Orientation Orientation
        {
            get { return (Orientation)GetValue(OrientationProperty); }
            set { SetValue(OrientationProperty, value); }
        }

        public static readonly DependencyProperty OrientationProperty =
            DependencyProperty.Register("Orientation", typeof(Orientation), typeof(WrapPanel),
                new PropertyMetadata(Orientation.Horizontal, OnOrientationPropertyChanged));

        private static void OnOrientationPropertyChanged(DependencyObject d,
            DependencyPropertyChangedEventArgs e)
        {
            WrapPanel source = (WrapPanel)d;
            Orientation value = (Orientation)e.NewValue;
            if (source.ignorePropertyChange)
            {
                source.ignorePropertyChange = false;
                return;
            }
            if ((value != Orientation.Horizontal) && (value != Orientation.Vertical))
            {
                source.ignorePropertyChange = true;
                source.SetValue(OrientationProperty, (Orientation)e.OldValue);
                throw new ArgumentException("OnOrientationPropertyChanged InvalidValue", "value");
            }
            source.InvalidateMeasure();
        }

        private static void OnItemHeightOrWidthPropertyChanged(DependencyObject d,
            DependencyPropertyChangedEventArgs e)
        {
            WrapPanel source = (WrapPanel)d;
            double value = (double)e.NewValue;
            if (source.ignorePropertyChange)
            {
                source.ignorePropertyChange = false;
                return;
            }
            if (!double.IsNaN(value) && ((value <= 0.0) || double.IsPositiveInfinity(value)))
            {
                source.ignorePropertyChange = true;
                source.SetValue(e.Property, (double)e.OldValue);
                throw new ArgumentException("OnItemHeightOrWidthPropertyChanged InvalidValue", "value");
            }
            source.InvalidateMeasure();
        }

        protected override Size MeasureOverride(Size constraint)
        {
            Orientation o = Orientation;
            OrientedSize lineSize = new OrientedSize(o);
            OrientedSize totalSize = new OrientedSize(o);
            OrientedSize maximumSize = new OrientedSize(o, constraint.Width, constraint.Height);
            double itemWidth = ItemWidth;
            double itemHeight = ItemHeight;
            bool hasFixedWidth = !double.IsNaN(itemWidth);
            bool hasFixedHeight = !double.IsNaN(itemHeight);
            Size itemSize = new Size(hasFixedWidth ? itemWidth : constraint.Width,
                hasFixedHeight ? itemHeight : constraint.Height);
            foreach (UIElement element in Children)
            {
                element.Measure(itemSize);
                OrientedSize elementSize = new OrientedSize(o,
                    hasFixedWidth ? itemWidth : element.DesiredSize.Width,
                    hasFixedHeight ? itemHeight : element.DesiredSize.Height);
                if (IsGreaterThan(lineSize.Direct + elementSize.Direct, maximumSize.Direct))
                {
                    totalSize.Direct = Math.Max(lineSize.Direct, totalSize.Direct);
                    totalSize.Indirect += lineSize.Indirect;
                    lineSize = elementSize;
                    if (IsGreaterThan(elementSize.Direct, maximumSize.Direct))
                    {
                        totalSize.Direct = Math.Max(elementSize.Direct, totalSize.Direct);
                        totalSize.Indirect += elementSize.Indirect;
                        lineSize = new OrientedSize(o);
                    }
                }
                else
                {
                    lineSize.Direct += elementSize.Direct;
                    lineSize.Indirect = Math.Max(lineSize.Indirect, elementSize.Indirect);
                }
            }
            totalSize.Direct = Math.Max(lineSize.Direct, totalSize.Direct);
            totalSize.Indirect += lineSize.Indirect;
            return new Size(totalSize.Width, totalSize.Height);
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            Orientation o = Orientation;
            OrientedSize lineSize = new OrientedSize(o);
            OrientedSize maximumSize = new OrientedSize(o, finalSize.Width, finalSize.Height);
            double itemWidth = ItemWidth;
            double itemHeight = ItemHeight;
            bool hasFixedWidth = !double.IsNaN(itemWidth);
            bool hasFixedHeight = !double.IsNaN(itemHeight);
            double indirectOffset = 0;
            double? directDelta = (o == Orientation.Horizontal) ?
                (hasFixedWidth ? (double?)itemWidth : null) :
                (hasFixedHeight ? (double?)itemHeight : null);
            UIElementCollection children = Children;
            int count = children.Count;
            int lineStart = 0;
            for (int lineEnd = 0; lineEnd < count; lineEnd++)
            {
                UIElement element = children[lineEnd];
                OrientedSize elementSize = new OrientedSize(o,
                    hasFixedWidth ? itemWidth : element.DesiredSize.Width,
                    hasFixedHeight ? itemHeight : element.DesiredSize.Height);
                if (IsGreaterThan(lineSize.Direct + elementSize.Direct, maximumSize.Direct))
                {
                    ArrangeLine(lineStart, lineEnd, directDelta, indirectOffset, lineSize.Indirect);
                    indirectOffset += lineSize.Indirect;
                    lineSize = elementSize;
                    if (IsGreaterThan(elementSize.Direct, maximumSize.Direct))
                    {
                        ArrangeLine(lineEnd, ++lineEnd, directDelta, indirectOffset, elementSize.Indirect);
                        indirectOffset += lineSize.Indirect;
                        lineSize = new OrientedSize(o);
                    }
                    lineStart = lineEnd;
                }
                else
                {
                    lineSize.Direct += elementSize.Direct;
                    lineSize.Indirect = Math.Max(lineSize.Indirect, elementSize.Indirect);
                }
            }
            if (lineStart < count)
            {
                ArrangeLine(lineStart, count, directDelta, indirectOffset, lineSize.Indirect);
            }
            return finalSize;
        }

        private void ArrangeLine(int lineStart, int lineEnd,
            double? directDelta, double indirectOffset, double indirectGrowth)
        {
            double directOffset = 0.0;
            Orientation o = Orientation;
            bool isHorizontal = o == Orientation.Horizontal;
            UIElementCollection children = Children;
            for (int index = lineStart; index < lineEnd; index++)
            {
                UIElement element = children[index];
                OrientedSize elementSize = new OrientedSize(o, element.DesiredSize.Width, element.DesiredSize.Height);
                double directGrowth = directDelta != null ? directDelta.Value : elementSize.Direct;
                Rect bounds = isHorizontal ?
                    new Rect(directOffset, indirectOffset, directGrowth, indirectGrowth) :
                    new Rect(indirectOffset, directOffset, indirectGrowth, directGrowth);
                element.Arrange(bounds);
                directOffset += directGrowth;
            }
        }
    }
}

In the WrapPanel.cs there are using statements to include the necessary functionality. The WrapPanel Class defines struct called OrientedSize which contains an Orientation along with Width and Height for the Size. The AreClose Method will be used to determine if elements are close together and IsGreaterThan determines if they are far apart. ItemHeight and ItemWidth are Properties that define the height and width of each item in the panel, the OnItemHeightOrWidthPropertyChanged handles when this changes. There’s an Orientation Property with an OnOrientationPropertyChanged Event to handle when this changes. MeasureOverride and ArrangeOverride are used when the layout of the Panel will be determined and will position the items within the Panel accordingly, along with ArrangeLine which will position elements in a line, until they need to be wrapped which will be the final look of the Control.

Step 8

Once done select from the Menu, Build, then Build Solution

vs2017-build-build-solution

Step 9

In the Solution Explorer select MainPage.xaml

vs2017-mainpage

Step 10

From the Menu choose View and then Designer

vs2017-view-designer

Step 11

The Design View will be displayed along with the XAML View and in this between the Grid and /Grid elements, enter the following XAML:

<local:WrapPanel Margin="10">
	<Rectangle Width="150" Height="150" Fill="Black"/>
	<Rectangle Width="150" Height="150" Fill="Gray"/>
	<Rectangle Width="150" Height="150" Fill="Red"/>
	<Rectangle Width="150" Height="150" Fill="Orange"/>
	<Rectangle Width="150" Height="150" Fill="Yellow"/>
	<Rectangle Width="150" Height="150" Fill="Green"/>
	<Rectangle Width="150" Height="150" Fill="Cyan"/>
	<Rectangle Width="150" Height="150" Fill="Blue"/>
	<Rectangle Width="150" Height="150" Fill="Magenta"/>
	<Rectangle Width="150" Height="150" Fill="Purple"/>
</local:WrapPanel>

The block of XAML represents a set of Rectangle Controls which will be contained within the WrapPanel – when the MainPage is narrower the items will be wrapped accordingly with fewer items being displayed per row to fit into the space available.

Step 12

That completes the Universal Windows Platform Application so Save the Project then in Visual Studio select the Local Machine to run the Application

vs2017-local-machine

Step 13

After the Application has started running it should then appear with the Wrap Panel displayed

ran-wrap-control

Step 14

To Exit the Application select the Close button in the top right of the Application

vs2017-close

Creative Commons License

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s