Search code examples
wpflistviewalignmentdatatemplatelistviewitem

Alignment in ListViewItem using DataTemplate


I'm using a ListView to show person first name and last name. I want to align the first name to the left and the last name to the right

I wrote the following code:

<Windows.Resources>
  <DataTemplate Datatype="{x:Type local:Person}">
  <StackPanel Orientation="Horizontel">
   <TextBlock Text="{Binding Path=FirstName}" TextAlignment="Left">
   <TextBlock Text="{Binding Path=LastName}" TextAlignment="Right">
  </StackPanel>
  </DataTemplates>
</Windows.Resources>

<ListView Name="myList", ItemSource="{Binding}" />

The ListView.DataContext connected to ObservableCollection

The result is that both first name and last name align to the left. I also tried to use DockPanel(How to make DockPanel fill available space) but it doesnt work.

Thanks,


Solution

  • I found the solution in this post: [https://www.stackoverflow.com/questions/10765652/how-to-right-align-content-in-a-datatemplate][]

    <Windows.Resources>
      <DataTemplate DataType="{x:Type local:Person}">
      <Grid>
       <Grid.ColumnDefinition>
         <ColumDefinition Width="*" />
         <ColumDefinition Width="Auto" />
       </Grid.ColumnDefinition>
       <TextBlock Text="{Binding Path=FirstName}" Grid.Column="0">
       <TextBlock Text="{Binding Path=LastName}" Grid.Column="1">
     </Grid>
     </DataTemplates>
    </Windows.Resources>
    
    <ListView Name="myList", ItemSource="{Binding}" HorzintalContentAlignment="Strech" />