C# Wpf重载Wrap排版自动换行(ArrangeOverride)

Xmal界面:


     
        
    

后台CS逻辑:

public class selPanel : WrapPanel
    {
        private double initW = 0;//初始宽度
        protected override Size ArrangeOverride(Size arrangeBounds)
        {
            Console.WriteLine("w:" + arrangeBounds.Width + " H:" + arrangeBounds.Height);
            Console.WriteLine("控件宽度:" + this.Width);

            if (initW > 0 && Math.Abs(initW - arrangeBounds.Width) < 30) return base.ArrangeOverride(arrangeBounds);//宽度变化明显重新计算
            initW = arrangeBounds.Width;
            double halfW = arrangeBounds.Width / 2;
            bool halfflag = true, fourflag = true;
            Size teSize = new Size(halfW, arrangeBounds.Height);//一半宽
            Size fSize = new Size(halfW / 2, arrangeBounds.Height);//1/4宽
            double minh = 0, maxh = 0;
            foreach (UIElement element in base.InternalChildren)
            {
                element.Measure(fSize);
                Size fourSize = element.DesiredSize;//宽度1/4时需要的高度

                element.Measure(teSize);
                Size halfSize = element.DesiredSize;//宽度一半时需要的高度

                element.Measure(arrangeBounds);
                Size acSize = element.DesiredSize;//完整大小时需要的高度


                minh = minh > 5 ? Math.Min(minh, acSize.Height) : acSize.Height;//5是随意给的
                maxh = Math.Max(maxh, acSize.Height);

                if (fourSize.Height > acSize.Height + 1)//+1给点冗余
                {
                    fourflag = false;
                }
                if (halfSize.Height > acSize.Height + 1)
                {
                    halfflag = false;
                }
            }
            if (maxh - minh < 15)//高度差太大,不美观,不在一行显示
            {
                if (fourflag)//可以显示四项
                {
                    this.ItemWidth = halfW / 2;
                    return new Size(0, 0);//增加性能 后面就不用算了
                }
                if (halfflag)//可以显示两项
                {
                    this.ItemWidth = halfW;
                    return new Size(0, 0);//增加性能 后面就不用算了
                }
            }

            return base.ArrangeOverride(arrangeBounds);
        }
    }

满足了选择题答案排版。

你可能感兴趣的:(C#)