随笔 - 705  文章 - 0  评论 - 1103  阅读 - 138万 

自定义布局控件

 

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:  }
posted on   冯瑞涛  阅读(523)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
历史上的今天:
2010-05-30 2010-5-30 难得休息
2010-05-30 2010-3-13 社区精英面对面 - 北京 Dev 组 2010 领袖 活动
2010-05-30 转:Community Clips 使用指南
点击右上角即可分享
微信分享提示