Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to stretch a Border to fill the width of a ListViewItem?

I have a ListView as follows:

<ListView ItemsSource="{Binding SerialNumbers}" SelectionMode="Multiple" HorizontalAlignment="Stretch">
    <ListView.ItemTemplate>
        <DataTemplate>
            <Border Background="Red" Padding="14 5" HorizontalAlignment="Stretch">
                <TextBlock HorizontalAlignment="Stretch" Text="{Binding Number}" />
                <behaviours:Interaction.Triggers>
                    <behaviours:EventTrigger EventName="MouseLeftButtonUp">
                        <behaviours:InvokeCommandAction Command="{Binding Path=DataContext.SerialNumberSelectedCommand, RelativeSource={RelativeSource AncestorType=UserControl}}" CommandParameter="{Binding}" />
                    </behaviours:EventTrigger>
                </behaviours:Interaction.Triggers>
            </Border>
         </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

I want the Border to take the full width as the ListViewItem, but it is not happening. I’ve tried adding HorizontalAlignment="Stretch" to the ListView, Border, and the TextBlock. It isn’t working. It currently looks like this.

border not stretching to full width

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I stretch the Border to get the full width of the ListViewItem.

I want to achieve this because I have a MouseLeftButtonUp event linked to the Border, which will call a command. As the Border is only the red part, it will only be called on clicking the red part. I want it to be called on clicking the total width of the ListViewItem.

>Solution :

In my opinion, the cleanest way to achieve it is to set HorizontalContentAlignment to the ListViewItem. You can easily achieve this using a style, like this:

<ListView>
  <ListView.ItemTemplate>
    <DataTemplate>
      <Border Background="Red" >
        <TextBlock Text="{Binding}"/>
      </Border>
     </DataTemplate>
   </ListView.ItemTemplate>
   <ListView.ItemContainerStyle>
     <Style TargetType="ListViewItem">
       <Setter Property="HorizontalContentAlignment" Value="Stretch" />
     </Style>
   </ListView.ItemContainerStyle>
 </ListView>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading