Hodaya Shalom
Hodaya Shalom

Reputation: 4417

Change the column width according to the contents

I have a DataGrid that his ItemSource binding to the following object:

public ObservableCollection<X> MyCollection{ get; set; }

Class X contains all the data to the DataGrid's columns

Example:

private string name;

public string Name
{
    get { return name; }
    set
    {
        name= value;
        NotifyPropertyChanged("Name");
    }
}

etc.

Is there anything I can to set in xaml to the width of the columns will be based on content (when the content will change the width will also change accordingly)?

I've seen a number of examples that do this in C# code, I want it to be done in XAML, is it possible?

EDIT:

DataGrid:

<DataGrid x:Name="DG" ItemsSource="{Binding}" AutoGenerateColumns="False">
  <DataGrid.Columns>
     <DataGridTextColumn Header="{x:Static p:Resources.Name}" Binding="{Binding Name}"></DataGridTextColumn>
     <DataGridTextColumn Header="{x:Static p:Resources.x}" Binding="{Binding X}"></DataGridTextColumn>
     <DataGridTextColumn Header="{x:Static p:Resources.y}" Binding="{Binding Y}"></DataGridTextColumn>
  </DataGrid.Columns>
</DataGrid>

Upvotes: 0

Views: 6768

Answers (2)

bryan
bryan

Reputation: 190

If you are explicitly defining your column in XAML like you are, just set the width to Auto. This should be the default though.

<DataGridTextColumn Width="Auto" Header="{x:Static p:Resources.Name}" Binding="{Binding Name}"></DataGridTextColumn>

Upvotes: 1

sa_ddam213
sa_ddam213

Reputation: 43596

You can set ColumnWidth="SizeToCells" this will work.

<DataGrid x:Name="DG" ColumnWidth="SizeToCells"  ItemsSource="{Binding}" AutoGenerateColumns="False">

Avaliable size modes for ColumnWidth

  • Auto The default automatic sizing mode sizes DataGrid columns based on the contents of both cells and column headers.
  • SizeToCells The cell-based automatic sizing mode sizes DataGrid columns based on the contents of cells in the column, not including column headers.
  • SizeToHeader The header-based automatic sizing mode sizes DataGrid columns based on the contents of column headers only.
  • Pixel The pixel-based sizing mode sizes DataGrid columns based on the numeric value provided.
  • Star(*) The star sizing mode is used to distribute available space by weighted proportions

Upvotes: 5

Related Questions