开发者

WPF DataGrid sizing content of a templated column

开发者 https://www.devze.com 2023-03-31 06:28 出处:网络
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;

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>

    &l开发者_开发百科t;!-- 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>


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

0

精彩评论

暂无评论...
验证码 换一张
取 消