WPF StackPanel自动调整大小

时间:2012-09-03 22:27:16

标签: c# wpf

我有一个名为mainCanvas的Canvas,我按照

的顺序以编程方式添加ScrollViewerStackPanel

... 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中且设置为:

宽度="自动"

高度="自动"

Horizo​​ntalAlignment ="拉伸"

VerticalAlignment ="拉伸"

我可以使用pnl.Height = 500;使工作变得半工作,这表明如果Stackpanel高度受限制,滚动条确实有效。但这只是手动将高度调整到全屏尺寸,因此在调整应用程序大小时不会自动调整大小。

我希望将pnl.Height = Double.NaN;设置为自动并将V / H调整设置为Stretch可以正常工作,但StackPanel仍然会将所有控件重叠到它的最大尺寸。

当我通过滚动调整父级和/或主应用程序窗口的大小时,有人能指出我正确的方向让我的StackPanel适合父mainCanvas并自动调整大小吗?

谢谢

2 个答案:

答案 0 :(得分:2)

我相信Canvas仅用于绝对定位。使用网格作为面板可能会给你想要的结果。

答案 1 :(得分:2)

正如您所注意到的,StackPanel不会伸展以填充其容器。但是您可以将其MinWidthMinHeight属性绑定到其容器的宽度/高度。

// 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);