WPF 控件模板:为什么指定没有 ColumnDefinations/RowDefinations 的 Grid 作为外部元素?
我一直在阅读《WPF 编程》,这是有关控制模板的示例之一:
<Button DockPanel.Dock="Bottom" x:Name="addButton" Content="Add">
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Ellipse Width="128" Height="32" Fill="Yellow" Stroke="Black" />
<ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center" />
</Grid>
</ControlTemplate>
</Button.Template>
</Button>
我想知道为什么使用网格而不是更简单的面板(例如画布)?因为我们没有贴花任何行/列?
谢谢!
I've been reading Programming WPF, here is one of the examples about Control Template:
<Button DockPanel.Dock="Bottom" x:Name="addButton" Content="Add">
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<Grid>
<Ellipse Width="128" Height="32" Fill="Yellow" Stroke="Black" />
<ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center" />
</Grid>
</ControlTemplate>
</Button.Template>
</Button>
I'm wondering why use a grid but not a simpler panel such as canvas? Since we didn't decalre any row/columns?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您未指定任何行或列,则每一行或列之一都是隐式的,因此为您提供一个网格单元格。因此,
Ellipse
和ContentPresenter
占据相同的网格单元。添加到同一单元格的项目的 z 顺序由它们添加的顺序决定。在这种情况下,ContentPresenter
将出现在Ellipse
的“顶部”。如果您使用
Canvas
而不是Grid
,子级的大小将不受容器大小的限制。这是因为Canvas
不会像Grid
那样对其子级施加任何大小限制。因此,您必须指定Ellipse
和ContentPresenter
的大小,并且您需要知道Canvas
的大小设置该大小。因此,使用Grid
会更容易、更直观。If you don't specify any rows or columns, one of each is implicit, therefore giving you a single grid cell. Thus, both the
Ellipse
andContentPresenter
occupy the same grid cell. The z-order of items added to the same cell is determined by the order in which they are added. In this case, theContentPresenter
will appear "on top of" theEllipse
.Were you to to use a
Canvas
instead of aGrid
, the size of the children would not be restricted by the size of the container. That's because aCanvas
does not impose any size restraints on its children like theGrid
does. Therefore, you'd have to specify a size for both theEllipse
andContentPresenter
, and you'd need to know the size of theCanvas
to set that size. Ergo, it's just a whole lot easier and more intuitive using aGrid
.