Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2017
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.87 KB | None | 0 0
  1. class CustomPanel : Panel
  2. {
  3.     public double MinItemWidth
  4.     {
  5.         get { return (double)GetValue(MinItemWidthProperty); }
  6.         set { SetValue(MinItemWidthProperty, value); }
  7.     }
  8.  
  9.     public static readonly DependencyProperty MinItemWidthProperty =
  10.         DependencyProperty.Register(nameof(MinItemWidth), typeof(double), typeof(CustomPanel), new PropertyMetadata(100.0, (d, e) => (d as CustomPanel)?.InvalidateMeasure()));
  11.  
  12.     protected override Size MeasureOverride(Size availableSize)
  13.     {
  14.         if (Children.Count > 0)
  15.         {
  16.             var numberOfChildrenPerRow = Math.Floor(availableSize.Width / MinItemWidth);
  17.             var widthPerChild = availableSize.Width / numberOfChildrenPerRow;
  18.  
  19.             foreach (UIElement child in Children)
  20.             {
  21.                 child.Measure(new Size(widthPerChild, availableSize.Height));
  22.                 availableSize.Height = Math.Max(availableSize.Height, child.DesiredSize.Height);
  23.             }
  24.         }
  25.  
  26.         if (Double.IsPositiveInfinity(availableSize.Height) || Double.IsPositiveInfinity(availableSize.Width))
  27.         {
  28.             return new Size(0, 0);
  29.         }
  30.  
  31.         return availableSize;
  32.     }
  33.  
  34.     protected override Size ArrangeOverride(Size finalSize)
  35.     {
  36.         double heightOfPreviousRows = 0;
  37.         double heightOfCurrentRow = 0;
  38.  
  39.         if (Children.Count > 0)
  40.         {
  41.             var numberOfChildrenPerRow = (int)Math.Floor(finalSize.Width / MinItemWidth);
  42.             var widthPerChild = finalSize.Width / numberOfChildrenPerRow;
  43.  
  44.             int i = 0;
  45.                
  46.             foreach (UIElement child in Children)
  47.             {
  48.                 if (i % numberOfChildrenPerRow == 0)
  49.                 {
  50.                     heightOfPreviousRows += heightOfCurrentRow;
  51.                     heightOfCurrentRow = 0;
  52.                 }
  53.  
  54.                 heightOfCurrentRow = Math.Max(heightOfCurrentRow, child.DesiredSize.Height);
  55.  
  56.                 var x = (i % numberOfChildrenPerRow) * widthPerChild;
  57.                 var y = heightOfPreviousRows;
  58.  
  59.                 child.Arrange(new Rect(new Point(x, y), new Size(widthPerChild, child.DesiredSize.Height)));
  60.  
  61.                 ++i;
  62.             }
  63.         }
  64.  
  65.         return finalSize;
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement