简体   繁体   English

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

[英]How to Add a Scrollbar to Window in C#

I have created a window as follows: 我创建了一个窗口如下:

Window myWindow = new Window();

How can I add a Vertical Scroll Bar to this Windows and make the Scroll Bar only visible if the Height isn't large enough to show all the elements. 如何在此窗口中添加垂直滚动条,并使滚动条仅在高度不足以显示所有元素时才可见。

You could add a ScrollViewer element to your window and put the necessary controls into the ScrollViewer control. 您可以将ScrollViewer元素添加到窗口,并将必要的控件放入ScrollViewer控件。

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

Or if you want to code it in the code-behind file you could write 或者,如果您想在代码隐藏文件中对其进行编码,则可以编写

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

You cannot add a scrollbar to a window itself. 您无法将滚动条添加到窗口本身。 You can only add scrollbars to controls. 您只能向控件添加滚动条。 IE to a grid inside your window. IE到窗口内的网格。

Example: 例:

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

EDIT: 编辑:

Just realized that Window also has a ScrollViewer property. 刚刚意识到Window也有ScrollViewer属性。 I'm not sure how this property works for a Window and how such a window would look like. 我不确定这个属性如何适用于Window以及这样一个窗口的样子。 Gave it a try, but no scrollbars show up. 试一试,但没有滚动条出现。

EDIT 2: 编辑2:

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

try this 尝试这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM