WPF 控件模板:为什么指定没有 ColumnDefinations/RowDefinations 的 Grid 作为外部元素?

发布于 2024-08-11 08:54:07 字数 600 浏览 1 评论 0原文

我一直在阅读《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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浪漫人生路 2024-08-18 08:54:07

如果您未指定任何行或列,则每一行或列之一都是隐式的,因此为您提供一个网格单元格。因此,EllipseContentPresenter 占据相同的网格单元。添加到同一单元格的项目的 z 顺序由它们添加的顺序决定。在这种情况下,ContentPresenter 将出现在 Ellipse 的“顶部”。

如果您使用 Canvas 而不是 Grid,子级的大小将不受容器大小的限制。这是因为 Canvas 不会像 Grid 那样对其子级施加任何大小限制。因此,您必须指定 EllipseContentPresenter 的大小,并且您需要知道 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 and ContentPresenter 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, the ContentPresenter will appear "on top of" the Ellipse.

Were you to to use a Canvas instead of a Grid, the size of the children would not be restricted by the size of the container. That's because a Canvas does not impose any size restraints on its children like the Grid does. Therefore, you'd have to specify a size for both the Ellipse and ContentPresenter, and you'd need to know the size of the Canvas to set that size. Ergo, it's just a whole lot easier and more intuitive using a Grid.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文