Reputation: 37
For certain reasons I need to add elements to my form with codebehind.
There is a main panel. By clicking a button - I am adding some content to it as below:
private void AddCodeKlantFieldButtonOnClick(object sender, RoutedEventArgs routedEventArgs)
{
var button = sender as Button;
if (button != null)
{
var panel = (StackPanel)button.Tag;
var stackPanel = new StackPanel { Orientation = Orientation.Horizontal };
AddLabel(stackPanel, "Klant van:", 135);
opzoekenLandVan = new OpzoekenCode(OpzoekenCodeTable.Klant, "");
opzoekenLandTot = new OpzoekenCode(OpzoekenCodeTable.Klant, "");
stackPanel.Children.Add(opzoekenLandVan);
AddLabel(stackPanel, "tot en met:", 100);
stackPanel.Children.Add(opzoekenLandTot);
var count = panel.Children.Count;
panel.Children.Insert(8, stackPanel);
}
}
That works fine! But if I add too much items, there is not enough space on the form - so a scrollviewer would be needed. I am quite new and can not figure out how to handle it. I tried this:
var scrollViewer = new ScrollViewer();
scrollViewer.Content = panel;
scrollViewer.Visibility = Visibility.Visible;
scrollViewer.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
scrollViewer.CanContentScroll = true;
But the scrollbar does not appear. If I try to add it to the form
panel.Children.Add(scrollViewer);
I am getting an error:
An exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll but was not handled in user code
Additional information: Logical tree depth exceeded while traversing the tree. This could indicate a cycle in the tree.
Upvotes: 1
Views: 782
Reputation: 1108
In the code below, you did not add the scrollViewer to the visual tree so it's not displaying
var scrollViewer = new ScrollViewer();
scrollViewer.Content = panel; //this does not add to visualtree
scrollViewer.Visibility = Visibility.Visible;
scrollViewer.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
scrollViewer.CanContentScroll = true;
one of the lines above is
scrollViewer.Content = panel;
so you will get an error on trying to add it to panel's children.
panel.Children.Add(scrollViewer);
You see the circular issue? First line, you put panel inside scrollViewer, next line you put the same scrollViewer in the panel.
Try commenting out scrollViewer.Content = panel but leave panel.Children.Add(scrollViwer) in, this should add the scrollViewer to the visualtree. But it'll probably be invisible due to 0 width or height since it has no content and is in a stackpanel.
Upvotes: 2