I'm experiencing an odd behavior with WPF.
My goal here is to have an ItemsControl
with a vertical line on each item's side going from the top to the bottom of the item. Being that the items may vary in height, I'm binding the Line
's Y2
property to the ActualHeight
of the StackPanel
belonging to the Grid
.
Here's the XAML:
<ItemsControl Grid.Row="1" BorderThickness="0" ItemsSource="{Binding ShipmentActivity}" >
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Name="ListBox">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Line Stroke="{StaticResource ButtonOutlineBrush}" X1="8" X2="8" Y1="0"
Y2="{Binding ActualHeight, ElementName=ShipmentActivity}"
StrokeThickness="1" />
<StackPanel Grid.Column="1" Margin=".1" x:Name="ShipmentActivity">
<StackPanel.Resources>
<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap"/>
</Style>
</StackPanel.Resources>
<TextBlock Text="{Binding Status}" FontWeight="SemiBold" FontSize="13" />
<TextBlock Text="{Binding Location}" Foreground="Gray"/>
<TextBlock Text="Wed, Sep 13, 2017, 8:29 PM (2 days ago)" Foreground="Gray"/>
</StackPanel>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Running this at first seems perfect. The problem is noticeable once I start to narrow the width of the window, causing the TextBlock
s to wrap, and in effect
causing the items to grow in height, and then resizing the window back to its original width (and beyond). Although the TextBlock
s are back to its original state (and height), the height of the items remain the same - stuck at its highest point, leaving huge gaps below the text, while the Line
's height doesn't shrink. The Line
is definitely the one to blame here, because removing the line removes the issue.
What is even stranger yet, is adding a margin to the StackPanel
even the slightest (.1) fixes the issue, and the items shrink back to its intended height.
Am I doing something wrong, or is this a bug?
I would use a Border element to decorate the StackPanel, rather than using a Line. Then just set the BorderThickness
property of the Border accordingly.
Hence your XAML would be like this:
<ItemsControl ...>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderThickness="1,0,0,0"
BorderBrush="{StaticResource ButtonOutlineBrush}">
<StackPanel ...>
You can use the Padding
property of the Border and/or the Margin
property of the StackPanel to space-out the two elements.