#1,000 – Displaying the Contents of a ListBox in a Circle

We can arrange the child elements of a ListBox into a circle by defining a new class that inherits from Panel, as follows:

    public class CircularPanel : Panel
    {
        protected override System.Windows.Size MeasureOverride(System.Windows.Size availableSize)
        {
            foreach (UIElement child in Children)
                child.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));

            return base.MeasureOverride(availableSize);
        }

        // Arrange stuff in a circle
        protected override System.Windows.Size ArrangeOverride(System.Windows.Size finalSize)
        {
            if (Children.Count > 0)
            {
                // Center & radius of panel
                Point center = new Point(finalSize.Width / 2, finalSize.Height / 2);
                double radius = Math.Min(finalSize.Width, finalSize.Height) / 2.0;
                radius *= 0.8;   // To avoid hitting edges

                // # radians between children
                double angleIncrRadians = 2.0 * Math.PI / Children.Count;

                double angleInRadians = 0.0;

                foreach (UIElement child in Children)
                {
                    Point childPosition = new Point(
                        radius * Math.Cos(angleInRadians) + center.X,
                        radius * Math.Sin(angleInRadians) + center.Y);

                    child.Arrange(new Rect(childPosition, child.DesiredSize));

                    angleInRadians += angleIncrRadians;
                }
            }

            return finalSize;
        }
    }

We can now use this panel as the ItemsPanel for a ListBox.

        <ListBox ItemsSource="{Binding ActorList}">
            <ListBox.ItemsPanel>
                <ItemsPanelTemplate>
                    <local:CircularPanel />
                </ItemsPanelTemplate>
            </ListBox.ItemsPanel>
        </ListBox>

1000-001
1000-002
(Thanks to Jobi Joy for an example of this).

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

6 Responses to #1,000 – Displaying the Contents of a ListBox in a Circle

  1. MiHa says:

    Congratulations! Half way done 🙂

  2. sshumakov says:

    Great example, thank you 🙂

  3. masoto says:

    Your solutions compile for me but the form is Blank after compilation @ Sean???

    • Sean says:

      What are you setting your data context to? And how are you populating the ActorList? You’ll notice that the ListBox binds to a property named ActorList, so you’ll need to properly set up an ActorList property and implement INotifyPropertyChanged, as appropriate. If you don’t understand how to populate a ListBox via data binding, take a look at posts #964-968.

Leave a comment