在Grid中的ListView项中换行文本

时间:2016-04-22 22:31:41

标签: c# .net wpf

如何在网格中包装文本?

在MainWindow.xaml

<Grid>
    <ListView Margin="10" Name="Users" >
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Name" Width="300" DisplayMemberBinding="{Binding Name}" />
                <GridViewColumn Header="Age" Width="200" DisplayMemberBinding="{Binding Age}" />
            </GridView>
        </ListView.View>
    </ListView>
</Grid>

在MainWindow.xaml.cs

public ObservableCollection<User> items = new ObservableCollection<User>();
items.Add(new User() { Name = "John", Age = 42 });
Users.ItemsSource = items;

1 个答案:

答案 0 :(得分:2)

您应为DataTemplate创建GridViewColumn并放置TextBlock。然后可以使用TextWrapping属性。工作示例:

<ListView Name="Users">
  <ListView.View>
    <GridView>            
        <GridViewColumn Header="Name" Width="385">
            <GridViewColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock TextWrapping="Wrap" Text="{Binding Name}" />
                </DataTemplate>
            </GridViewColumn.CellTemplate>
        </GridViewColumn>
        <GridViewColumn Header="Age" Width="385">
            <GridViewColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock TextWrapping="Wrap" Text="{Binding Age}" />
                </DataTemplate>
            </GridViewColumn.CellTemplate>
        </GridViewColumn>
    </GridView>
  </ListView.View>
</ListView>