使用DataTemplate在ListViewItem中对齐

时间:2015-07-09 14:19:14

标签: wpf listview alignment datatemplate listviewitem

我使用ListView显示人名和姓氏。 我想将第一个名称与左侧对齐,将姓氏与右侧对齐

我写了以下代码:

<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}" />

ListView.DataContext连接到ObservableCollection

结果是名字和姓氏都对齐到左边。 我也试过使用DockPanel(How to make DockPanel fill available space) 但它不起作用。

谢谢,

2 个答案:

答案 0 :(得分:0)

我在这篇文章中找到了解决方案:[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" />

答案 1 :(得分:0)

您可以使用DockPanel

 <Windows.Resources>
  <DataTemplate DataType="{x:Type local:Person}">
  <DockPanel>
     <TextBlock Text="{Binding Path=FirstName}"  HorizontalAlignemnt="Left">
     <TextBlock Text="{Binding Path=LastName}" HorizontalAlignemnt="Right">
 </DockPanel>
 </DataTemplates>
 </Windows.Resources>

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