如何在C#中添加滚动条到窗口

时间:2011-05-20 07:36:34

标签: c# wpf window vertical-scrolling

我创建了一个窗口如下:

Window myWindow = new Window();

如何在此窗口中添加垂直滚动条,并且只有在高度不足以显示所有元素时才能显示滚动条。

3 个答案:

答案 0 :(得分:52)

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

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

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

ScrollViewer viewer = new ScrollViewer();
viewer.VerticalScrollBarVisibility = ScrollBarVisibility.Auto;
// append scroll viewer to window

答案 1 :(得分:2)

您无法将滚动条添加到窗口本身。您只能向控件添加滚动条。 I.E.到窗口内的网格。

示例:

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

修改

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

编辑2:

ScrollViewer sv = new ScrollViewer();
sv.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
myGrid.Children.Add(sv);

答案 2 :(得分: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 };
            }