-
Notifications
You must be signed in to change notification settings - Fork 4
/
GridPanel.cs
94 lines (77 loc) · 3.16 KB
/
GridPanel.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
namespace XP
{
/// <summary>
/// 将所给区域划分为指定列
/// </summary>
public class GridPanel : Panel
{
public int Columns
{
get { return (int)GetValue(ColumnsProperty); }
set { SetValue(ColumnsProperty, value); }
}
public static readonly DependencyProperty ColumnsProperty =
DependencyProperty.Register("Columns", typeof(int), typeof(GridPanel),
new FrameworkPropertyMetadata(1, FrameworkPropertyMetadataOptions.AffectsArrange |
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
new PropertyChangedCallback(ColumnsChanged),
new CoerceValueCallback(CoerceColumns)));
private static object CoerceColumns(DependencyObject d, object baseValue)
{
if ((int)baseValue < 0)
return 1;
return baseValue;
}
private static void ColumnsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
}
protected override System.Windows.Size MeasureOverride(System.Windows.Size availableSize)
{
if (this.InternalChildren.Count == 0)
return new Size(0, 0);
foreach (UIElement child in this.InternalChildren)
{
child.Measure(availableSize);
}
UIElement child1 = this.InternalChildren[0];
// 每个元素的大小一样
double width = double.IsInfinity(availableSize.Width) ? child1.DesiredSize.Width * this.Columns : availableSize.Width;
double height = child1.DesiredSize.Height * this.InternalChildren.Count / this.Columns;
return new Size(width, height);
}
protected override System.Windows.Size ArrangeOverride(System.Windows.Size finalSize)
{
if (this.InternalChildren.Count == 0)
return new Size(0, 0);
UIElement child1 = this.InternalChildren[0];
int row = (int)Math.Ceiling(this.InternalChildren.Count / (double)this.Columns);
// 尽可能给多少用多少
double totalWidth = double.IsInfinity(finalSize.Width) ? child1.DesiredSize.Width * this.Columns : finalSize.Width;
double totalHeight = double.IsInfinity(finalSize.Height) ?
child1.DesiredSize.Height * row : finalSize.Height;
// 每个元素的大小一样
double width = totalWidth / this.Columns;
double height = totalHeight / row;
int i = 0, j = 0;
foreach (UIElement child in this.InternalChildren)
{
child.Arrange(new Rect(i * width, j * height, width, height));
i++;
if(i == this.Columns)
{
i = 0;
j++;
}
}
return new Size(totalWidth, totalHeight);
}
}
}