从带换行的文本框中获取 LineCount

我想获得带包装的文本框的行数。以下代码不起作用。


void txt_Loaded(object sender, RoutedEventArgs e)

{

       TextBox t = (TextBox)sender;

       var count = t.LinesCount; // wrong;

       // or

       var lineCount = t.Text.Split(new[] {'\n','r'}).length;

}

我有三行,但var lineCount = t.Text.Split(new[] {'\n','r'}).length;返回 4。


慕田峪9158850
浏览 277回答 3
3回答

慕容森

如果您正在寻找换行的数量,您可以使用GetLineIndexFromCharacterIndex()。作为参数,您可以传递最后一个字符(对应于Text.Lenght)。int WrappedLines1 = TextBox.GetLineIndexFromCharacterIndex(TextBox.Text.Length) + 1;或TextBox.LineCount()。第一个方法返回一个从零开始的索引,第二个方法从 1 开始计数。int WrappedLines2 = TextBox.LineCount;物理行数(由换行分隔的行)可以用 计算Split().Count()。int LineFeedsCount = TextBox.Text.Split(new[] { "\n" }, StringSplitOptions.None).Count();如果您不想计算空行,请 StringSplitOptions.RemoveEmptyEntries用作选项参数。您可以验证行数是否正确,将TextWrapping属性设置为.NoWrap并使用 计算行数.LineCount。TextBox1.TextWrapping = TextWrapping.NoWrap;int LineFeedsCount = TextBox1.LineCount;

暮色呼如

您的代码中有拼写错误,正在查找字母r而不是回车符\r尝试 var lineCount = t.Text.Split(new[] {'\n','\r'}).length;另一种选择是按上述方式拆分,然后将每行的长度除以一行中可以包含的字符数。您可能需要计算此值,因为 TextBox 似乎没有Columns属性。

呼如林

我想我找到了LineCount不工作的原因。`TextBox 实际上在 DataColumn 中。我将宽度设置为 2*。<telerik:GridViewDataColumn Header="Info" DataMemberBinding="{Binding Info}"&nbsp; Width="2*">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <telerik:GridViewDataColumn.CellTemplate>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <DataTemplate>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <TextBox&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; AcceptsReturn="True"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; TextWrapping="Wrap"&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Text="{Binding Info, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Loaded="TextBox_Loaded"/>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </DataTemplate>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </telerik:GridViewDataColumn.CellTemplate>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </telerik:GridViewDataColumn>`.&nbsp;Width 属性会导致此问题。如果我删除它,那么它就可以工作。但我需要宽度,不知道为什么以及如何?
打开App,查看更多内容
随时随地看视频慕课网APP