BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Data Display Controls - ListView

The one hundred and sixth part of the Windows Presentation Foundation Fundamentals tutorial returns to the topic of the WPF controls. This article looks at ListView, which is the first of the data display controls.

Column Resizing and Reordering

GridViews include standard functionality that permits the user to resize and reorder the columns. If you point to the vertical bar between two headers, the mouse pointer changes to indicate that the column can be resized. Dragging this area changes the size for the entire column. If you drag the column header itself, whilst the mouse is not near the header's edge, the column can be moved across, changing the order.

If you do not wish to permit reordering of columns, you can disable the feature by setting the GridView's AllowColumnReorder property to false:

<GridView AllowsColumnReorder="False">

Cell Templates

The use of data binding expressions for the DisplayMemberBinding property provides some flexibility in the output. However, if you cannot achieve the results you need using this property, you may decide to use a data template for one or more columns. This allows much greater flexibility because you can use any WPF controls within the grid's cells, each bound to a different element of the underlying objects, if desired.

To change the template for a column's cells, you set the CellTemplate property of the GridViewColumn object. The value used must be a data template. In order for the CellTemplate property to be recognised, you must also remove the DisplayMemberBinding property from the column.

The following updated column definitions provide a simple example. Here the second and third columns are updated to use TextBlocks with differing foreground colours. The bindings have also been modified so that the creation times and the file lengths are formatted.

Replace the three column definitions with the following XAML:

<GridViewColumn DisplayMemberBinding="{Binding FullName}" Header="Full Name" Width="200"/>
<GridViewColumn Header="Creation Time" Width="125">
    <GridViewColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding CreationTime,StringFormat='yyyy-MM-dd HH:mm:ss'}"/>
        </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Header="Size" Width="100">
    <GridViewColumn.CellTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Length,StringFormat='N0'}"/>
        </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>

Run the program and refresh the grid to see the results. The new colours and formatting should be visible.

WPF ListView with Cell Templates

23 October 2014