书上说Grid,SrackPane,Canvas都是从Panel类中继承来的,如果想要自己写一个DIY的控件,就需要重写Panel中的ArrangeOverride和MeasureOverride方法;笔者刚开始在书上看了一个自定义控件——蜂窝式控件。效果如下图所示:
然后自己有查阅资料自己做了一个锯齿状的DIY控件,效果如下图所示:
其实做这样的控件并不困难,至于要重写Panel类中的ArrangeOverride和MeasureOverride方法即可;
MeasureOverride方法是定义一个控件大小,ArrangeOverride方法是排列所定义的控件;
蜂窝状控件实现步骤如下:
一:创建一个class文件;
二:继承panel类;
三:在类中插入如下代码;
protected override Size MeasureOverride(Size availableSize) { int i = 0; foreach (FrameworkElement child in Children) { if (i < 15) { child.Measure(new Size(100, 100));//自定义一个宽度和长度 } else { child.Measure(new Size(0, 0)); } i++; } return new Size(600, 600); } protected override Size ArrangeOverride(Size finalSize) { UIElementCollection mychildren = Children; int count = mychildren.Count; for (int i = 0; i < count; i++) { Point cellOrigin = GetCellOrigin(i); //坐标 double dw = mychildren[i].DesiredSize.Width; double dh = mychildren[i].DesiredSize.Height; mychildren[i].Arrange(new Rect(cellOrigin.X, cellOrigin.Y, dw, dh));//排列控件 //Rect描述矩形的宽度、高度和位置。x System.Double 矩形左边的 x 坐标位置。y System.Double 矩形上边的 y 坐标位置。 } return new Size(300, 600); } protected Point GetCellOrigin(int cellIndex) { int cellRow, cellColomn; cellColomn = cellIndex % 3; cellRow = cellIndex / 3; int x, y; x = cellColomn * 100; y = cellRow * 100; if (cellColomn == 1) y += 50; Point cellOrigin = new Point(x, y); return cellOrigin; }
锯齿状控件代码如下:
protected override Size MeasureOverride(Size availableSize) { int i = 0; foreach (UIElement ue in Children) { if (i < 6) { ue.Measure(new Size(100, 100)); i++; } else { ue.Measure(new Size(0, 0)); } } return new Size(200, 600); } protected override Size ArrangeOverride(Size finalSize) { UIElementCollection child = Children; int count = child.Count; for (int i = 0; i < count; i++) { Point pt = setPoint(i); double width = child[i].DesiredSize.Width; double height = child[i].DesiredSize.Height; child[i].Arrange(new Rect(pt.X, pt.Y, width, height)); } return new Size(200, 600); } protected Point setPoint(int index) { int cellColomn; cellColomn = index % 2; int x, y; y = index * 80; x = cellColomn * 100; if (cellColomn == 1) { x -= 20; } Point pt = new Point(x,y); return pt; }