WPF DataGrid 调整模板列内容的大小
我有一个包含 2 个模板列的 DataGrid:
第一个包含一个组合框,我让它调整大小以适合其内容,因为最多只有一两个单词;
第二个包含一个文本框,其中文本可能会变得有点长。
因此,在这里我设置了 MaxWidth=somevalue 以避免其宽度扩展到数据网格容器之外,我对其 MaxHeight 执行了相同的操作,并将文本设置为换行。无论如何,我希望文本框调整其宽度大小以填充数据网格容器中的所有剩余空间:如果用户缩小或放大第二列,我希望文本框相应地缩小或放大,以便它们的宽度保持在同步。文本将换行,并根据需要出现滚动条。
网格中的两个控件都绑定到 MVVM 场景中的数据源。谁能给出让模板文本框宽度随容器列扩展/收缩的提示?这是我的示例代码:
<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>
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在
TextBox
上设置HorizontalAlignment="Stretch"
并设置 DataGrid 的列Width="*"
Set
HorizontalAlignment="Stretch"
on yourTextBox
and set your DataGrid's ColumnWidth="*"