Search code examples
wpflistboxdatatemplate

How to utilise the space within a ListBoxItem WPF


<DataTemplate x:Key="dtTeamInGame">
        <WrapPanel MaxHeight="20" >
            <Label x:Name="txtPath" Content="{Binding Path = FirstName, Mode=TwoWay}" MinWidth="35" FontStretch="Expanded" ></Label>
            <Label x:Name="txtPath2" Content="{Binding Path = SurName, Mode=TwoWay}" MinWidth="125"  ></Label>
        </WrapPanel>
</DataTemplate>


<ListBox  x:Name="listBox" ItemTemplate="{DynamicResource dtTeamInGame}" HorizontalAlignment="Left" Height="100" Margin="97,206,0,0" VerticalAlignment="Top" Width="381">
        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem"  BasedOn="{StaticResource {x:Type ListBoxItem}}">
                <EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListViewItem_PreviewMouseLeftButtonDownHome" />
            </Style>
        </ListBox.ItemContainerStyle>
</ListBox>

I have two labels within my data template and I would like to see all the text within my label but the text is clipping off. I would like to see all the text and the text should be centered. I have increased the height of the labels but the text is not centered. This problem came about when I set the wrap panel max height to 20 and I need it to be 20. I would like to center the text vertically with the same font size. I have set the minimum height of the labels to 30 but the text is not centered vertically.

The clipping of the label within a list box

The clipping of the label within a list box


Solution

  • Set the Padding property of the Label elements to 0 or use TextBlocks:

    <DataTemplate x:Key="dtTeamInGame">
        <WrapPanel MaxHeight="20">
            <Label x:Name="txtPath" Content="FirstName" MinWidth="35" FontStretch="Expanded" Padding="0"></Label>
            <Label x:Name="txtPath2" Content="Surname" MinWidth="125" Padding="0"></Label>
        </WrapPanel>
    </DataTemplate>