2
votes

Is there a way (without codebehind) to make a WPF ListView grow to the width or height of its contents rather than scroll? Sort of like a StackPanel only still selectable.

For instance, if I have:

<ScrollViewer>
  <StackPanel>
    <ListView ItemsSource="{Binding Rail1}">
      <ListView.ItemsPanel>
        <ItemsPanelTemplate>
          <StackPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
      </ListView.ItemsPanel>
    </ListView>
    <ListView ItemsSource="{Binding Rail2}">
      <ListView.ItemsPanel>
        <ItemsPanelTemplate>
          <StackPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
      </ListView.ItemsPanel>
    </ListView>
  </StackPanel>
</ScrollViewer>

the ScrollViewer does not show a horizontal scroll bar, instead the ListViews do.

2
Do you have any styles or anything else set on ListViews? Or some special data in Rail1, Rail2? Your sample works fine if you add HorizontalScrollBarVisibility="Auto" into scrollViewer. - Snowbear
Sorry. I forgot to mention that I used a StackPanel as the ItemsPanel for the listview. I'm trying to get the growth to be horizontal, not vertical. Maybe a StackPanel isn't the correct choice for ItemsPanel? - Daniel

2 Answers

1
votes

It depends on container. Add ListView itself to the ScrollViewer - it should do the trick.

<ScrollViewer HorizontalScrollBarVisibility="Auto">
    <StackPanel>
        <ListView ItemsSource="{Binding Rail1}" > 
            <ListView.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal" />
                </ItemsPanelTemplate>
            </ListView.ItemsPanel>
        </ListView>
        <ListView ItemsSource="{Binding Rail2}" >
            <ListView.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal" />
                </ItemsPanelTemplate>
            </ListView.ItemsPanel>
        </ListView>
    </StackPanel>
</ScrollViewer>
1
votes

It depends on it's container, but if you set the HorizontalAlignment property to "Stretch" and the ListView's container will allow it, it should size itself to its content.

* Edit ** If you want both ListView's not to scroll then do something like:

<ScrollViewer>
   <DockPanel>
      <ListView ItemsSource="{Binding Rail1}" DockPanel.Dock="Top" />
      <ListView ItemsSource="{Binding Rail2}" DockPanel.Dock="Top" />
   </DockPanel>
</ScrollViewer>

I think this will give you what you want.