码迷,mamicode.com
首页 > Windows程序 > 详细

wpf ListBox,item两列不等高。

时间:2015-07-31 12:22:44      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

  业务有这样的需求,类似瀑布流。内容两列不等高展示。

只需要继承panel,重写MeasureOverride和ArrangeOverride方法就行了。

 很简单,内容都在代码里。

技术分享

 

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace XXXXXX
{
    public class TwoColumnPanel : Panel
    {
        /// <summary>
        /// 先测量需要多大尺寸,做个申报准备
        /// </summary>
        /// <param name="constraint">限定的尺寸,比如,规定了width和height</param>
        /// <returns></returns>
        protected override Size MeasureOverride(Size constraint)
        {
            //定义预期的宽度和高度
            double height = 0, height1 = 0, height2 = 0, width = 0;
            UIElement element;
            if (Children.Count > 0)
            { 
                element = Children[0];
                width = element.DesiredSize.Width*2;
            }
            //遍历每个元素,计算所需的总尺寸
            for (int i = 0; i < Children.Count; i++)
            {
                element = Children[i];
                //按照限定的尺寸测量一下自己,拿镜子找着自己
                element.Measure(constraint);
                if (i % 2 == 0)
                {
                    height1 += element.DesiredSize.Height;
                }
                else
                {
                    height2 += element.DesiredSize.Height;
                }
            }
            height = height1 > height2 ? height1 : height2;

            //申报,我需要这个尺寸
            return new Size(width, height);
        }

        /// <summary>
        /// 排列每个元素
        /// </summary>
        /// <param name="arrangeBounds">测量的尺寸</param>
        /// <returns></returns>
        protected override Size ArrangeOverride(Size arrangeBounds)
        {
            double currentX2 = 0,currentY1 = 0,currentY2 = 0;
            UIElement element;

            if (Children.Count > 0)
            {
                element = Children[0];
                currentX2 = element.DesiredSize.Width;
            }

            for (int i = 0; i < Children.Count; i++)
            {
                element = Children[i];
                //排列每个元素
                if (i % 2 == 0)
                {
                    Children[i].Arrange(new Rect(0, currentY1, element.DesiredSize.Width, element.DesiredSize.Height));
                    currentY1 += element.DesiredSize.Height;
                }
                else
                {
                    Children[i].Arrange(new Rect(currentX2, currentY2, element.DesiredSize.Width, element.DesiredSize.Height));
                    currentY2 += element.DesiredSize.Height;
                }
                
            }
            return arrangeBounds;
        }
    }
}

  

wpf ListBox,item两列不等高。

标签:

原文地址:http://www.cnblogs.com/m7777/p/4691533.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!