Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF DataGrid sizing content of a templated column

Tags:

wpf

datagrid

I have a DataGrid with 2 templated columns:

  • the first includes a combobox and I let it size to fit its content, as this is at most one or two words;

  • the second instead includes a textbox where text might become somewhat long.

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>
like image 247
Naftis Avatar asked Aug 25 '11 15:08

Naftis


1 Answers

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

like image 94
Rachel Avatar answered Sep 28 '22 10:09

Rachel