WPF:如何使画布自动调整大小? [英] WPF: How to make canvas auto-resize?

查看:41
本文介绍了WPF:如何使画布自动调整大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的 Canvas 自动调整其项目的大小,以便 ScrollViewer 滚动条具有正确的范围.这可以在 XAML 中完成吗?

I would like my Canvas to automatically resize to the size of its items, so that the ScrollViewer scroll bars have the correct range. Can this be done in XAML?

<ScrollViewer HorizontalScrollBarVisibility="Auto" x:Name="_scrollViewer">
    <Grid x:Name ="_canvasGrid" Background="Yellow">
        <Canvas x:Name="_canvas" HorizontalAlignment="Left" VerticalAlignment="Top" Background="Green"></Canvas>
        <Line IsHitTestVisible="False" .../>
    </Grid>
</ScrollViewer>

在上面的代码中,画布的大小始终为 0,但它不会剪裁其子项.

In the above code the canvas always has size 0, though it doesn't clip its children.

推荐答案

不,这是不可能的(请参阅下面的 MSDN 片段).但是,如果您想要滚动条和自动调整大小,请考虑使用 Grid 代替,并使用 Margin 属性将您的项目放置在此 Grid 上.. Grid 会告诉 ScrollViewer 他想要多大是,你会得到滚动条.. Canvas 总是会告诉 ScrollViewer 他不需要任何尺寸.. :)

No this is not possible (see snippet from MSDN below). However, if you want to have scrollbars and auto-resizing, consider using a Grid instead, and use the Margin property to position your items on this Grid.. Grid will tell the ScrollViewer how big he wants to be, and you will get the scrollbars.. Canvas will always tells the ScrollViewer he doesn't need any size.. :)

网格让您同时享受两个世界 - 只要您将所有元素放入一个单元格中,您就可以同时获得:任意定位和自动调整大小.一般来说,最好记住大多数面板控件(DockPanel、StackPanel 等)都可以通过 Grid 控件实现.

Grid lets you enjoy both worlds - As long as you're putting all elements into a single cell, you get both: Arbitrary positioning and auto-sizing. In general it is good to remember that most panel controls (DockPanel, StackPanel, etc) can be implemented via a Grid control.

来自 MSDN:

Canvas 是唯一没有固有布局特征的面板元素.Canvas 的默认 Height 和 Width 属性为零,除非它是自动调整其子元素大小的元素的子元素.Canvas 的子元素永远不会调整大小,它们只是定位在指定的坐标处.这为不需要或不需要固有大小限制或对齐的情况提供了灵活性.对于您希望子内容自动调整大小和对齐的情况,通常最好使用 Grid 元素.

Canvas is the only panel element that has no inherent layout characteristics. A Canvas has default Height and Width properties of zero, unless it is the child of an element that automatically sizes its child elements. Child elements of a Canvas are never resized, they are just positioned at their designated coordinates. This provides flexibility for situations in which inherent sizing constraints or alignment are not needed or wanted. For cases in which you want child content to be automatically resized and aligned, it is usually best to use a Grid element.

希望能帮到你

这篇关于WPF:如何使画布自动调整大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆