How to automate and align GridViewColumn data with right justification in WPF?

How can I:

  • right align text in ID column
  • make each of the columns automatic size according to the text length of the cell with the longest visible data?

Here is the code:

<ListView Name="lstCustomers" ItemsSource="{Binding Path=Collection}"> <ListView.View> <GridView> <GridViewColumn Header="ID" DisplayMemberBinding="{Binding Id}" Width="40"/> <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" Width="100" /> <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}"/> </GridView> </ListView.View> </ListView> 

partial answer:

Thanks Kjetil, GridViewColumn.CellTemplate works well, and Auto Width works, of course, but when the ObservativeCollection "Collection" is updated with longer column width data, the column sizes are not updated themselves, so this is only a solution for the initial data display:

 <ListView Name="lstCustomers" ItemsSource="{Binding Path=Collection}"> <ListView.View> <GridView> <GridViewColumn Header="ID" Width="Auto"> <GridViewColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding Id}" TextAlignment="Right" Width="40"/> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" Width="Auto" /> <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}" Width="Auto"/> </GridView> </ListView.View> </ListView> 
+74
listview wpf gridview xaml gridviewcolumn
Feb 18 '09 at 10:52
source share
9 answers

To make each of the autosize columns, you can set Width = "Auto" to the GridViewColumn.

To align the text in the ID column, you can create a cell template using TextBlock and set TextAlignment. Then set ListViewItem.HorizontalContentAlignment (using the installer style in ListViewItem) so that the cell template fills the entire GridViewCell.

There may be a simpler solution, but this should work.

Note: the solution requires both HorizontalContentAlignment = Stretch in Window.Resources and TextAlignment = Right in CellTemplate.

 <Window x:Class="WpfApplication6.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Window.Resources> <Style TargetType="ListViewItem"> <Setter Property="HorizontalContentAlignment" Value="Stretch" /> </Style> </Window.Resources> <Grid> <ListView Name="lstCustomers" ItemsSource="{Binding Path=Collection}"> <ListView.View> <GridView> <GridViewColumn Header="ID" Width="40"> <GridViewColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding Id}" TextAlignment="Right" /> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" Width="Auto" /> <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}" Width="Auto"/> </GridView> </ListView.View> </ListView> </Grid> </Window> 
+92
Feb 18 '09 at 11:23
source share

If the width of the content changes, you will need to use this bit of code to update each column:

 private void ResizeGridViewColumn(GridViewColumn column) { if (double.IsNaN(column.Width)) { column.Width = column.ActualWidth; } column.Width = double.NaN; } 

You will have to run it every time the data for this column is updated.

+33
Dec 19 '09 at 0:14
source share

If your list is also resettable, you can use the behavior pattern to resize the columns to fit the full width of the ListView. Almost the same as you use grid.column definitions

 <ListView HorizontalAlignment="Stretch"     Behaviours:GridViewColumnResize.Enabled="True">    <ListViewItem></ListViewItem>    <ListView.View>      <GridView>        <GridViewColumn  Header="Column *"                    Behaviours:GridViewColumnResize.Width="*" >          <GridViewColumn.CellTemplate>            <DataTemplate>              <TextBox HorizontalAlignment="Stretch" Text="Example1" />            </DataTemplate>          </GridViewColumn.CellTemplate> 

See the following link for some examples and the link to the source code http://lazycowprojects.tumblr.com/post/7063214400/wpf-c-listview-column-width-auto

+17
Jun 30 2018-11-11T00:
source share

I created the following class and used it wherever required instead of GridView :

 /// <summary> /// Represents a view mode that displays data items in columns for a System.Windows.Controls.ListView control with auto sized columns based on the column content /// </summary> public class AutoSizedGridView : GridView { protected override void PrepareItem(ListViewItem item) { foreach (GridViewColumn column in Columns) { // Setting NaN for the column width automatically determines the required // width enough to hold the content completely. // If the width is NaN, first set it to ActualWidth temporarily. if (double.IsNaN(column.Width)) column.Width = column.ActualWidth; // Finally, set the column with to NaN. This raises the property change // event and re computes the width. column.Width = double.NaN; } base.PrepareItem(item); } } 
+9
Apr 01 '13 at 14:13
source share

Since I had an ItemContainerStyle, I had to put a HorizontalContentAlignment in an ItemContainerStyle

  <ListView.ItemContainerStyle> <Style TargetType="ListViewItem"> <Style.Triggers> <DataTrigger Binding="{Binding Path=FieldDef.DispDetail, Mode=OneWay}" Value="False"> <Setter Property="Visibility" Value="Collapsed"/> </DataTrigger> </Style.Triggers> <Setter Property="HorizontalContentAlignment" Value="Stretch" /> .... 
+7
Aug 01 '11 at 16:03
source share

I liked the user1333423 solution, except that it always resized each column; I needed to allow some columns to be fixed width. Thus, in this version, columns with a width set to "Auto" will be automatically set, and those set to a fixed amount will not be automatically set.

 public class AutoSizedGridView : GridView { HashSet<int> _autoWidthColumns; protected override void PrepareItem(ListViewItem item) { if (_autoWidthColumns == null) { _autoWidthColumns = new HashSet<int>(); foreach (var column in Columns) { if(double.IsNaN(column.Width)) _autoWidthColumns.Add(column.GetHashCode()); } } foreach (GridViewColumn column in Columns) { if (_autoWidthColumns.Contains(column.GetHashCode())) { if (double.IsNaN(column.Width)) column.Width = column.ActualWidth; column.Width = double.NaN; } } base.PrepareItem(item); } } 
+4
15 '15 at 7:32
source share

I know this is too late, but here is my approach:

 <GridViewColumn x:Name="GridHeaderLocalSize" Width="100"> <GridViewColumn.Header> <GridViewColumnHeader HorizontalContentAlignment="Right"> <Grid Width="Auto" HorizontalAlignment="Right"> <Grid.ColumnDefinitions> <ColumnDefinition Width="100"/> </Grid.ColumnDefinitions> <TextBlock Grid.Column="0" Text="Local size" TextAlignment="Right" Padding="0,0,5,0"/> </Grid> </GridViewColumnHeader> </GridViewColumn.Header> <GridViewColumn.CellTemplate> <DataTemplate> <TextBlock Width="{Binding ElementName=GridHeaderLocalSize, Path=Width, FallbackValue=100}" HorizontalAlignment="Right" TextAlignment="Right" Padding="0,0,5,0" Text="Text" > </TextBlock> </DataTemplate> </GridViewColumn.CellTemplate> 

The basic idea is to bind the width of the cellTemplete to the width of the ViewGridColumn. Width = 100 - The default width used before the first resize. No codes. Everything in xaml.

+2
May 25 '15 at 7:39
source share

I had problems with the accepted answer (because I skipped the HorizontalAlignment = Stretch part and adjusted the original answer).

This is another method. It uses a grid with a SharedSizeGroup.

Note: Grid.IsSharedScope = true in ListView.

 <Window x:Class="WpfApplication6.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="300" Width="300"> <Grid> <ListView Name="lstCustomers" ItemsSource="{Binding Path=Collection}" Grid.IsSharedSizeScope="True"> <ListView.View> <GridView> <GridViewColumn Header="ID" Width="40"> <GridViewColumn.CellTemplate> <DataTemplate> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" SharedSizeGroup="IdColumn"/> </Grid.ColumnDefinitions> <TextBlock HorizontalAlignment="Right" Text={Binding Path=Id}"/> </Grid> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn Header="First Name" DisplayMemberBinding="{Binding FirstName}" Width="Auto" /> <GridViewColumn Header="Last Name" DisplayMemberBinding="{Binding LastName}" Width="Auto"/> </GridView> </ListView.View> </ListView> </Grid> </Window> 
+1
Dec 24 '10 at 17:13
source share

I created a function to update the GridView column headings for a list and will call it whenever the window is resized or the list changes its layout.

 public void correctColumnWidths() { double remainingSpace = myList.ActualWidth; if (remainingSpace > 0) { for (int i = 0; i < (myList.View as GridView).Columns.Count; i++) if (i != 2) remainingSpace -= (myList.View as GridView).Columns[i].ActualWidth; //Leave 15 px free for scrollbar remainingSpace -= 15; (myList.View as GridView).Columns[2].Width = remainingSpace; } } 
+1
Jul 31 '14 at 13:01
source share



All Articles