How to Add a Scrollbar to Window in C#

后端 未结 3 2013
你的背包
你的背包 2021-01-07 18:05

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

相关标签:
3条回答
  • 2021-01-07 18:48

    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 };
                }
    
    0 讨论(0)
  • 2021-01-07 18:52

    You could add a ScrollViewer element to your window and put the necessary controls into the ScrollViewer control.

    <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
    
    0 讨论(0)
  • 2021-01-07 18:58

    You cannot add a scrollbar to a window itself. You can only add scrollbars to controls. I.E. to a grid inside your window.

    Example:

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

    EDIT:

    Just realized that Window also has a ScrollViewer property. I'm not sure how this property works for a Window and how such a window would look like. Gave it a try, but no scrollbars show up.

    EDIT 2:

    ScrollViewer sv = new ScrollViewer();
    sv.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
    myGrid.Children.Add(sv);
    
    0 讨论(0)
提交回复
热议问题