wpf 控件开发基础(6) -单一容器(Decorator)
2010-04-06 23:51 Clingingboy 阅读(3386) 评论(0) 编辑 收藏 举报其实这部分的文章已经很多了,写下来方便自己查询.
wpf内置提供了很多容器(Panel),容器分为多容器和单容器.下面介绍单容器.内置的单容器,大家最熟悉的如Border,其作用用于装饰容器内的元素,单一容器继承自Decorator,下面来看一个未使用装饰器的例子.
<Window x:Class="WPFControlTutorialPart6_WPFApp.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:control="clr-namespace:WPF.Controls;assembly=WPF.Controls" Title="Window1" Height="300" Width="300"> <Grid> <Button>Hello World</Button> </Grid> </Window>
可以看到一个Button控件填充了整个窗体。一般我们只需要显示正常大小的Button即可.
容器计算规则
计算容器的大小是一个递归的过程,永远是先测量(MeasureOverride)子元素,然后通知父元素分配空间.计算好空间后然后排列(ArrangeOverride),如果测量大小过度ArrangeOverride会自动进行修正的.自定义一个单容器来修正上面的布局
public class PixelSnapper : Decorator { protected override Size ArrangeOverride(Size finalSize) { Point location = this.CalculateOffset(finalSize, this.Child); location.X = Math.Round(location.X); location.Y = Math.Round(location.Y); this.Child.Arrange(new Rect(location, this.Child.DesiredSize)); return finalSize; } private Point CalculateOffset(Size finalSize, UIElement ui) { Point point = new Point(0.0, 0.0); if (ui is FrameworkElement) { FrameworkElement element = ui as FrameworkElement; Size desiredSize = element.DesiredSize; switch (element.HorizontalAlignment) { case HorizontalAlignment.Left: point.X = element.Margin.Left; break; case HorizontalAlignment.Center: point.X = (((finalSize.Width - desiredSize.Width) + base.Margin.Left) - base.Margin.Right) / 2.0; break; case HorizontalAlignment.Right: point.X = (finalSize.Width - element.Margin.Right) - desiredSize.Width; break; } switch (element.VerticalAlignment) { case VerticalAlignment.Top: point.Y = element.Margin.Top; return point; case VerticalAlignment.Center: point.Y = (((finalSize.Height - desiredSize.Height) + base.Margin.Top) - base.Margin.Bottom) / 2.0; return point; case VerticalAlignment.Bottom: point.Y = (finalSize.Height - element.Margin.Bottom) - desiredSize.Height; return point; } } return point; } }
wpf内置的BulletDecorator.如内置的CheckBox和RadioButton都是BulletDecorator,左边是符号,右侧是Content
示例
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
2007-04-06 Subtext--为skin准备相关文件加载
2007-04-06 Subtext中的skin实现方法