Windows Phone 自定义布局控件,继承Panel
2011-05-30 09:23 闫妍 阅读(252) 评论(0) 编辑 收藏 举报自定义布局控件
01: using System; 02: using System.Net; 03: using System.Windows; 04: using System.Windows.Controls; 05: using System.Windows.Documents; 06: using System.Windows.Ink; 07: using System.Windows.Input; 08: using System.Windows.Media; 09: using System.Windows.Media.Animation; 10: using System.Windows.Shapes; 11: 12: namespace Demos7 13: { 14: public class CellsPanel:Panel 15: { 16: //重写测量方法 17: protected override Size MeasureOverride(Size availableSize) 18: { 19: int i = 0; 20: foreach (FrameworkElement child in Children) 21: { 22: if (i < 15) 23: { 24: //为前15个可放在这个容器中的元素分配100×100的空间 25: child.Measure(new Size(100, 100)); 26: } 27: else 28: { //15个之后的呢,就不显示了。 29: child.Measure(new Size(0, 0)); 30: } 31: i++; 32: } 33: return new Size(300,600);//总大小 34: } 35: 36: //重写排列方法 37: protected override Size ArrangeOverride(Size finalSize) 38: { 39: UIElementCollection mychildren = Children; //Children 是Panel父类的共有成员 40: int count = mychildren.Count; 41: for (int i = 0; i < count; i++) //遍历每一个成员 42: { 43: Point cellOrigin = GetCellOrigin(i);//计算左上角的位置 44: double dw = mychildren[i].DesiredSize.Width;//宽度值 45: double dh = mychildren[i].DesiredSize.Height;//高度值 46: mychildren[i].Arrange(new Rect(cellOrigin.X, cellOrigin.Y, dw, dh));//排列元素的位置及他的宽度和高度 47: } 48: return new Size(300, 600); 49: } 50: 51: //计算索引为cellIndex的子元素的左上角位置 52: protected Point GetCellOrigin(int cellIndex) 53: { 54: int cellRow, cellColomn; 55: cellColomn = cellIndex % 3; 56: cellRow = cellIndex / 3; 57: 58: int x, y; 59: x = cellColomn * 100; 60: y = cellRow * 100; 61: if (cellColomn == 1) y += 50; 62: 63: Point cellOrigin = new Point(x, y); 64: return cellOrigin; 65: } 66: 67: } 68: }