简体   繁体   English

C#DataGridTextColumn换行符

[英]C# DataGridTextColumn line break

There must be a simple solution for this, but I just can't find it. 对此必须有一个简单的解决方案,但我只是找不到。 I have a DataGrid with DataGridTextColumns which contain data. 我有一个带有包含数据的DataGridTextColumns的DataGrid。 This is working fine. 一切正常。 I just seem to not get the String inside the Cells to make a line break, instead everything is in one line (no matter how long the string is). 我似乎只是没有使String进入单元格内以换行,而是一切都在一行中(无论字符串有多长)。

dataGrid.IsReadOnly = true;
dataGrid.AutoGenerateColumns = false;
dataGrid.ItemsSource = ConvertListIntoPlantViewModel(lList);

DataGridTextColumn textColumn1 = new DataGridTextColumn();
DataGridTextColumn textColumn2 = new DataGridTextColumn();
DataGridTextColumn textColumn3 = new DataGridTextColumn();
textColumn3.MaxWidth = 200;

textColumn1.Header = "Name";
textColumn1.Binding = new Binding("Name");
textColumn2.Header = "Type";
textColumn2.Binding = new Binding("Type");
textColumn3.Header = "Info";
textColumn3.Binding = new Binding("Information");

dataGrid.Columns.Add(textColumn1);
dataGrid.Columns.Add(textColumn2);
dataGrid.Columns.Add(textColumn3);

Let's say I want to make the Text, which ends up in textColumn3 to make a line break at the end of the cell (which is 200 wide). 假设我要制作文本,该文本以textColumn3结尾,以在单元格的末尾(200宽)换行。 How do I achieve this? 我该如何实现? There must be a simple Style Element that can be set, right? 必须有一个可以设置的简单样式元素,对吗? I just can't find it. 我只是找不到。

Help would be appreciated, thanks! 帮助将不胜感激,谢谢!

There must be a simple Style Element that can be set, right? 必须有一个可以设置的简单样式元素,对吗? I just can't find it. 我只是找不到。

Yes, you could set the ElementStyle property of the column(s) to the following Style for the text to wrap: 是的,您可以将列的ElementStyle属性设置为以下样式,以使文本换行:

<Style TargetType="TextBlock">
    <Setter Property="TextWrapping" Value="Wrap" />
</Style>

You could create the Style programmatically using the XamlReader.Parse method: 您可以使用XamlReader.Parse方法以编程方式创建Style:

string xaml = "<Style xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" TargetType=\"TextBlock\"><Setter Property=\"TextWrapping\" Value=\"Wrap\"/></Style>";
Style style = System.Windows.Markup.XamlReader.Parse(xaml) as Style;

DataGridTextColumn textColumn1 = new DataGridTextColumn();
textColumn1.ElementStyle = style;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM