问题
I have a ListBox with Expanders which in turn contains a ListBox. I would like to have both the ListBox with Expanders (listBox1) and the ListBox inside each Expander (listBox2) to have scroll functionality, but I cannot get the innermost scrolling to work (i.e. scrollViewer1 in my XAML).
How can I get both scrollbars to work?
<ScrollViewer x:Name="scrollViewer1">
<ListBox x:Name="listBox1" ItemsSource="{Binding Data}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Expander>
<Expander.Header>
<TextBlock Text="{Binding Name}">
</TextBlock>
</Expander.Header>
<ScrollViewer x:Name="scrollViewer2">
<ListBox x:Name="listBox2" ItemsSource="{Binding Numbers}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Grid>
<TextBlock Grid.Column="0" Text="{Binding}"/>
</Grid>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</ScrollViewer>
</Expander>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
回答1:
First of all, you d'ont need the scrollviewer tags: The listbox handles the scrolling by itself. To control the visibilty of the listbox scrollbar you ca use the ScrollViewer.HorizontalScrollBarVisibility
and ScrollViewer.VerticalScrollBarVisibility
.
Second, the vertical scrollbar of the inner listbox does not appear because without height limitations the listbox will expand to display all the items.
Here is a working code wich shows both scroll bar of parent and inner listbox :
<Window x:Class="StackOverflow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ListBox x:Name="listBox1" ItemsSource="{Binding Clients}">
<ListBox.ItemTemplate>
<DataTemplate>
<Expander>
<Expander.Header>
<TextBlock Text="{Binding Name}">
</TextBlock>
</Expander.Header>
<ListBox x:Name="listBox2" ItemsSource="{Binding Children}" MaxHeight="150">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Grid>
<TextBlock Grid.Column="0" Text="{Binding Name}"/>
</Grid>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Expander>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
To reproduce your problem, just remove the MaxHeight on the second listbox.
来源:https://stackoverflow.com/questions/32648912/scrollviewer-in-expander