Search code examples
c#wpfsizedatatemplateitemtemplate

WPF ItemTemplate Causing ListBox Content Size Issue


In a WPF project, I have a ListBox that renders correctly if I manually insert items in XAML, e.g.:

<ListBoxItem>
    <Grid Background="#7F271043" Width="200" Height="200">
        <Grid.RowDefinitions>
            <RowDefinition Height="110" />
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>

        <Image Grid.Row="0" Source="Logo-40p.png" HorizontalAlignment="Center" Margin="10,10,10,10" />
        <TextBlock Grid.Row="1" Text="Test Item" Foreground="White" Margin="10,0,10,0" FontSize="16" VerticalAlignment="Center" />
        <local:Rating Grid.Row="2" HorizontalAlignment="Left" Height="24" Margin="10,0,0,0" VerticalAlignment="Center" Width="130" SelectedValue="4" IsReadOnly="True" />
        <TextBlock Grid.Row="2" Text="Free" Foreground="#FF969292" Margin="0,0,10,0" FontSize="14" HorizontalAlignment="Right" VerticalAlignment="Center" />
    </Grid>
</ListBoxItem>

The bottom of the ListBoxItem looks like:

Manual Item Insertion

However, the moment I swap out <ListBoxItem> for:

<ListBox.ItemTemplate>
    <DataTemplate>

Even if I keep everything else identical, it creates a sizing problem with my rating control that I'm unable to fix (doesn't respond to manual size or stretch settings):

ItemTemplate

Any thoughts on how to address this? Do ItemTemplate / DataTemplate do something that might cause a control to not respect the size manually set or set by the grid row it's in?


Solution

  • Managed to fix this - it seems that a manually defined ListBoxItem in XAML behaves differently from the output of an ItemTemplate / DataTemplate.

    My rating user control had a set height and width specified that were overridden by the implementation XAML (height/width/stretch) inside a ListBoxItem but not inside a ItemTemplate / DataTemplate:

    mc:Ignorable="d" Height="750" Width="4070" MouseLeave="UserControl_MouseLeave">
    

    So I instead changed Height / Width to DesignHeight / DesignWidth to fix the issue:

    mc:Ignorable="d" d:DesignHeight="750" d:DesignWidth="4070" MouseLeave="UserControl_MouseLeave">