0
votes

I have a Canvas named mainCanvas and I'm programatically adding a ScrollViewer and a StackPanel to it in order of

...mainCanvas

......scrollView

.........pnl

............ (more stacked controls)

I'm attempting to get my StackPanel to auto size to the mainCanvas size and allow scrolling when it's too large. Code so far is below

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

Unfortunately, the StackPanel doesn't fit to the parent and doesn't autosize.

mainCanvas already exists in XAML with settings:

Width= "Auto"

Height= "Auto"

HorizontalAlignment = "Stretch"

VerticalAlignment = "Stretch"

I can get things semi-working by using pnl.Height = 500; which shows me the scrollbar does work if the Stackpanel height is restricted. But this is just manually fitting the height to the full screen size and so doesn't autosize when resizing the app.

I hoped setting pnl.Height = Double.NaN; to auto and V/H adjustment to Stretch would work but the StackPanel still overlaps all controls to it's maximum size.

Can anyone point me in the right direction to get my StackPanel to fit the parent mainCanvas and autosize when I resize either the parent and/or the main app window with scrolling?

Thank you

2

2 Answers

2
votes

I believe Canvas is for absolute positioning only. Using a Grid as your panel instead would probably give you the desired result.

2
votes

The StackPanel won't stretch to fill its container, as you noticed. But you can bind its MinWidth and MinHeight properties to its container's width/height.

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