我需要在dinamically创建一些FrameworkElements。我有一个StackPanel,我在其内部创建了一个Pivot,有一个PivotItem,在ScrollViewer里面有一个StackPanel和Buttons,如下所示:
Pivot pivot = new Pivot();
PivotItem pivotItem = new PivotItem();
pivot.Items.Add(pivotItem);
ScrollViewer scrollViewer = new ScrollViewer();
StackPanel stackContent = new StackPanel();
scrollViewer.Content = stackContent;
pivotItem.Content = scrollViewer;
stackContent.Children.Add(new Button() { Content = "button 1" });
stackContent.Children.Add(new Button() { Content = "button 2" });
stackContent.Children.Add(new Button() { Content = "button 3" });
stackContent.Children.Add(new Button() { Content = "button 4" });
stackContent.Children.Add(new Button() { Content = "button 5" });
stackContent.Children.Add(new Button() { Content = "button 6" });
stackContent.Children.Add(new Button() { Content = "button 7" });
stackContent.Children.Add(new Button() { Content = "button 8" });
stackContent.Children.Add(new Button() { Content = "button 9" });
stackContent.Children.Add(new Button() { Content = "button 10" });
stackContent.Children.Add(new Button() { Content = "button 11" });
stkPanel.Children.Add(pivot);
这是C#XAML代码:
<StackPanel x:Name="stkPanel">
</StackPanel>
如果我尝试在XAML中创建所有元素,ScrollViewer会按预期工作,但我需要在页面中发生某些事件时动态创建它们。
在调试中检查页面,PivotItem有&#34; ActualHeight == 0&#34;,所以我想其中的ScrollViewer不能用于这个原因,但我不知道如何解决它,也许某种方式对ScrollViewer说#34;给自己充电&#34;滚动工作。
答案 0 :(得分:1)
问题是StackPanel。正如Schumi1331所说,堆栈面板使用了所需的空间,儿子从来没有定义宽度或高度,而scrollViewer不能按预期工作。如果我改变网格,工作正常。
另一个解决方案是在插入dinnamics元素之后计算使用此元素的空间大小,并将高度设置为StackPanel。
答案 1 :(得分:0)
您需要将IsVerticalScrollEnabled设置为true,为您的元素提供MaxHeight 但更好的解决方案是ListView或GridView为它们提供Max Height属性,之后您希望滚动条出现。
<StackPanel x:Name="stkPanel" isVerticalScrollEnabled = "true" MaxHeight="300">
</StackPanel>
答案 2 :(得分:0)
Pivot pivot = new Pivot();
PivotItem pivotItem = new PivotItem();
pivot.Items.Add(pivotItem);
ScrollViewer scrollViewer = new ScrollViewer();
StackPanel stackContent = new StackPanel();
scrollViewer.Content = stackContent;
Window.Current.Activate();
var bounds = ApplicationView.GetForCurrentView().VisibleBounds;
scrollViewer.Height = bounds.Height;
pivotItem.Content = scrollViewer;
stackContent.Children.Add(new Button() { Content = "button 1" });
stackContent.Children.Add(new Button() { Content = "button 2" });
stackContent.Children.Add(new Button() { Content = "button 3" });
stackContent.Children.Add(new Button() { Content = "button 4" });
stackContent.Children.Add(new Button() { Content = "button 5" });
stackContent.Children.Add(new Button() { Content = "button 6" });
stackContent.Children.Add(new Button() { Content = "button 7" });
stackContent.Children.Add(new Button() { Content = "button 8" });
stackContent.Children.Add(new Button() { Content = "button 9" });
stackContent.Children.Add(new Button() { Content = "button 10" });
stackContent.Children.Add(new Button() { Content = "button 11" });
stkPanel.Children.Add(pivot);