Naftis
Naftis

Reputation: 4559

WPF DataGrid sizing content of a templated column

I have a DataGrid with 2 templated columns:

So here I set MaxWidth=somevalue to avoid its width expand beyond the datagrid container, I do the same for its MaxHeight, and set text to wrap. Anyway, I'd like the textbox to size its width to fill all the remaining space in the datagrid container: if the user shrinks or enlarges the 2nd column, I'd like the textbox to shrink or enlarge accordingly so that their width stay in synch. Text will wrap, and scrollbars appear as necessary.

Both controls in the grid are bound to a data source in a MVVM scenario. Could anyone give a hint for letting the template textbox width expand/contract with the container column? Here is my sample code:

<DataGrid ...>
  <DataGrid.Columns>
    <!-- 1 -->
    <DataGridTemplateColumn ...>
      <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
          <ComboBox .../>
        </DataTemplate>
      </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>

    <!-- 2: THIS TEXTBOX SHOULD EXPAND/CONTRACT WITH ITS CONTAINER COLUMN -->
    <DataGridTemplateColumn ...>
      <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
          <TextBox TextWrapping="Wrap"
               MinWidth="400" MaxWidth="700"
               MaxHeight="400"
               ScrollViewer.VerticalScrollBarVisibility="Auto" .../>
        </DataTemplate>
      </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
  </DataGrid.Columns>
</DataGrid>

Upvotes: 5

Views: 5624

Answers (1)

Rachel
Rachel

Reputation: 132658

Set HorizontalAlignment="Stretch" on your TextBox and set your DataGrid's Column Width="*"

Upvotes: 8

Related Questions