I have a window that contains a ItemsControl that can have a variable number of controls inside. In order to account for the case where there are more than will fit in the window height, I wrapped it in a ScrollViewer, so that a scrollbar would be shown when the number of items was more than would fit in the height available.
Now, the problem is that sometimes there won't be anything to show in the ItemsControl and sometimes there will. Therefore, I set the grid row's height to Auto to allow the ItemsControl to disappear when empty, or grow when needed. However, this means that the row takes as much height as it needs, even if this exceeds the window height, and the vertical scrollbar is never shown.
Here is some XAML for a sample window that demonstrates the issue...
<Window x:Class="DuplicateCustomerCheck.TestScrollViewerWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Test Scroll Viewer Window"
Height="450"
Width="200">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBox Name="N"
TextChanged="TextBoxBase_OnTextChanged"
Grid.Row="0"
Margin="3" />
<Grid Margin="3"
Grid.Row="1">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Text="Possible duplicate of..."
Margin="3" />
<ScrollViewer VerticalScrollBarVisibility="Visible"
Grid.Row="1">
<ItemsControl Name="MatchingNames"
ItemsSource="{Binding MatchingNames, Mode=TwoWay}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Item}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
</Grid>
<TextBlock Grid.Row="2"
Margin="3"
Text="Stuff at the bottom" />
</Grid>
</Window>
For demonstration purposes, here is the button's event handler that allows me to test different numbers of items (note that this is noddy code, so no error-checking etc)...
private void TextBoxBase_OnTextChanged(object sender, TextChangedEventArgs e) {
MatchingNames.ItemsSource = Enumerable
.Range(0, int.Parse(N.Text))
.Select(n1 => new {
Item = "Button " + n1
});
}
If I change the second grid row's height to * then it works fine, but this means that the ItemsControl is permanently visible, which I don't want. It should only be shown when there are some items in it.
I tried the ScrollViewerMaxSizeBehavior behaviour from this blog post (code here), but it didn't make any difference.
Anyone any idea how I can allow the ItemsControl to take as much vertical space as it needs, including zero, but not grow taller than can fit in the window?