22

我创建了一个窗口,如下所示:

Window myWindow = new Window();

如何在此 Windows 中添加垂直滚动条并仅在高度不足以显示所有元素时才使滚动条可见。

4

3 回答 3

58

您可以在窗口中添加一个ScrollViewer元素,并将必要的控件放入ScrollViewer控件中。

<ScrollViewer VerticalScrollBarVisibility="Auto">
    ...
</ScrollViewer>

或者,如果您想在代码隐藏文件中对其进行编码,您可以编写

ScrollViewer viewer = new ScrollViewer();
viewer.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
// append scroll viewer to window
于 2011-05-20T07:44:56.070 回答
2

您不能将滚动条添加到窗口本身。您只能向控件添加滚动条。IE 到窗口内的网格。

例子:

<Grid  ScrollViewer.CanContentScroll="True"
       ScrollViewer.HorizontalScrollBarVisibility="Auto">
   ...
</Grid>

编辑:

刚刚意识到 Window 也有一个 ScrollViewer 属性。我不确定这个属性如何用于 Window 以及这样的窗口会是什么样子。试一试,但没有滚动条出现。

编辑2:

ScrollViewer sv = new ScrollViewer();
sv.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
myGrid.Children.Add(sv);
于 2011-05-20T07:39:19.547 回答
0

试试这个

var xpage = your user control or page to which scroll bar need to be added at runtime

            xpage.SetValue(ScrollViewer.CanContentScrollProperty, true);
            xpage.SetValue(ScrollViewer.HorizontalScrollBarVisibilityProperty, ScrollBarVisibility.Auto);
            xpage.SetValue(ScrollViewer.VerticalScrollBarVisibilityProperty, ScrollBarVisibility.Auto);

            var scrollViewer = xpage.Content as ScrollViewer;
            if (scrollViewer != null)
            {
                var content = scrollViewer.Content;
                scrollViewer.Content = null;
                xpage.Content = content;
            }
            else
            {
                var content = xpage.Content;
                xpage.Content = null;
                xpage.Content = new ScrollViewer { Content = content };
            }
于 2017-12-08T05:08:48.013 回答