WPF-自定义瀑布流面板

效果

子控件的宽度全部一样,新增的子控件会追加到当前最矮的列最下方。

源码

WaterfallPanel.cs

using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace WeChatInteract.CustomControls
{
   
    /// 
    /// 瀑布流布局,等列宽
    /// 
    public class WaterfallPanel : Panel
    {
   
        public WaterfallPanel()
        {
   
        }

        /// 
        /// 列数
        /// 
        public int ColumnCount
        {
   
            get {
    return (int)this.GetValue(ColumnCountProperty); }
            set {
    this.SetValue(ColumnCountProperty, value); }
        }

        public static readonly DependencyProperty ColumnCountProperty = DependencyProperty.Register("ColumnCount", typeof(int), typeof(WaterfallPanel), new PropertyMetadata(PropertyChanged));

        public static void PropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
   
            if (sender == null || e.NewValue == e.OldValue)
                return;
            sender.SetValue(ColumnCountProperty, e.NewValue);

        }

        protected override Size MeasureOverride(Size availableSize)
        {
   
            if (Children.Count <= 0)
                return new Size(0,0);
            
            #region 测量值
            //Canvase、ScrollView等会给出无穷宽高
            Size childrenAvailableSize = new Size(double.IsPositiveInfinity(availableSize.Width) ? double.PositiveInfinity : availableSize.Width / ColumnCount, double.PositiveInfinity);
            Size[] childrenDesiredSizes = new Size[Children.Count];

            double[] columnH = new double[ColumnCount];
            double[] columnW = new double[ColumnCount];//列最宽元素的宽度
            for (int i = 0; i < ColumnCount; i++)
            {
   
                columnW[i] = 0;
                columnH[i] = 0;
            }
            for (int i = 0; i < Children.Count; i++)
     

你可能感兴趣的:(WPF)