1
votes

I have a WrapPanel inside a ScrollViewer. I measured out my layout that if 6 buttons can only fit in a fixed area on the Window of a width of 1920. But what I now want is that if there are more than 6 buttons on the page, I want the scroll viewer to show and scroll horizontally.

My desired layout would be to have the initial layout be of 6 buttons. 2 rows x 3 in each row. If there are more than 6, the next button(s) would show in the scrollable area triggering the scroll view to show. I am thinking that I may need to dynamically create StackPanels with "groups" of 6 buttons. If the button amount created is greater than 6, dynamically create a new StackPanel and add the next "group" of 6 buttons in that but then add that new StackPanel to the ScrollViewer. Am I correct in this assumption or is there a more efficient way to achieve this?

(NOTE): I just found that I can not add more than one StackPanel to a ScrollViewer. So is there a better way to do this?

How would I achieve this?

This is my current XAML layout with my WrapPanel.

<ScrollViewer Margin="0,100,0,0" Height="750" HorizontalScrollBarVisibility="Auto" Width="1920">
        <WrapPanel x:Name="stkPnlProductCategories" Height="Auto" Width="1920">

        <!-- This is filled in dynamically at runtime
            <controls:btnLarge Height="325" Width="500" Margin="20,0" TitleText="My Title" NoteText="" ShowNote="Collapsed" ShowSubTitle="Collapsed"/>
        -->

        </WrapPanel>
    </ScrollViewer>
1
Can you bind to an items.count on your buttons and if > 6 do a change on like the VerticalScrollbarVisibility from Disabled to True on the ScrollViewer? - Chris W.

1 Answers

1
votes

Ok, so instead of making <WrapPanel> a fixed width, use something adaptable like a

<StackPanel Orientation="Horizontal"></StackPanel>

The benefit of this, is that it will actually use that handy attribute of the <ScrollViewer> that you already have typed out there, HorizontalScrollBarVisibility="Auto".

That ought to do the trick. I have to say though, you want to avoid hard-coding widths, like you seem to be doing a lot. Sometimes it even saves effort to have the width adapt to the window size. Just a thought.

Edit: As far as trying to put in multiple StackPanels into a ScrollViewer, ScrollViewers can only contain one child element. That just means that if you want two StackPanels inside, then you need to wrap them in something else. For instance, you can put just a simple Grid

<ScrollViewer>
  <Grid>
    <StackPanel Orientation="Horizontal"></StackPanel>
    <StackPanel Orientation="Horizontal"></StackPanel>
  </Grid>
</ScrollViewer>

or another StackPanel

<ScrollViewer>
  <StackPanel Orientation="Vertical">
    <StackPanel Orientation="Horizontal"></StackPanel>
    <StackPanel Orientation="Horizontal"></StackPanel>
  </StackPanel>
</ScrollViewer>