[英]WPF StackPanel autosize
我有一个名为mainCanvas的Canvas
以编程方式向其中添加了ScrollViewer
和StackPanel
... mainCanvas
滚动视图......
......... PNL
............(更多堆叠控件)
我正在尝试使我的StackPanel自动调整为mainCanvas大小,并在其太大时允许滚动。 到目前为止的代码如下
mainCanvas.Children.Clear();
// Create the container
ScrollViewer scrollView = new ScrollViewer();
scrollView.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
scrollView.CanContentScroll = true;
scrollView.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
scrollView.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
StackPanel pnl = new StackPanel();
//pnl.Height = 500; //Works and allows scrolling but doesn't resize
pnl.Height = Double.NaN; //(Double.NaN is Auto) Doesn't Work - StackPanel overflows parent window
pnl.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
pnl.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
scrollView.Content = pnl;
// Add the ScrollView and StackPanel to Parent Window
mainCanvas.Children.Add(scrollView);
不幸的是,StackPanel不适合父级,并且不会自动调整大小。
mainCanvas
已存在于XAML中,具有以下设置:
宽度=“自动”
身高=“自动”
HorizontalAlignment =“拉伸”
VerticalAlignment =“拉伸”
我可以通过使用pnl.Height = 500;
来使事情pnl.Height = 500;
这显示了如果Stackpanel高度受到限制,滚动条确实可以工作。 但这只是手动将高度调整为全屏大小,因此在调整应用大小时不会自动调整大小。
我希望设置pnl.Height = Double.NaN;
进行自动调整,将“ V / H”调整为“拉伸”即可,但是StackPanel仍将所有控件重叠到最大尺寸。
当我通过滚动调整父窗口和/或主应用程序窗口的大小时,谁能指出正确的方向以使我的StackPanel适合父mainCanvas并自动调整大小?
谢谢
我相信Canvas仅用于绝对定位。 相反,使用网格作为面板可能会给您所需的结果。
正如您所注意到的, StackPanel
不会拉伸以填充其容器。 但是您可以将其MinWidth
和MinHeight
属性绑定到其容器的宽度/高度。
// give the canvas a name, so you can bind to it
mainCanvas.Name = "canvas";
// create the binding for the Canvas's "ActualHeight" property
var binding = new System.Windows.Data.Binding();
binding.ElementName = "canvas";
binding.Path = new PropertyPath("ActualHeight");
// assign the binding to the StackPanel's "MinHeight" dependency property
sp.SetBinding(StackPanel.MinHeightProperty, binding);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.