从包装的文本框中获取LineCount

时间:2018-06-07 18:03:22

标签: c# .net wpf textbox

我想通过包装得到多少行文本框。以下代码无效。

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.

3 个答案:

答案 0 :(得分:0)

您的代码中有拼写错误并且正在寻找字母r而不是回车\r

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

另一种选择是如上所述进行拆分,然后将每行的长度除以单行上可以包含的字符数。您可能需要计算它,因为看起来TextBox没有Columns属性。

答案 1 :(得分:0)

如果您正在寻找包裹线的数量,可以使用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;

答案 2 :(得分:0)

我想我找到了LineCount无效的原因。

TextBox实际上位于DataColumn中。我将宽度设置为2 *。

<telerik:GridViewDataColumn Header="Info" DataMemberBinding="{Binding Info}"  Width="2*">
                <telerik:GridViewDataColumn.CellTemplate>
                    <DataTemplate>
                        <TextBox
                            AcceptsReturn="True"
                            TextWrapping="Wrap" 
                            Text="{Binding Info, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                            Loaded="TextBox_Loaded"/>
                    </DataTemplate>
                </telerik:GridViewDataColumn.CellTemplate>
            </telerik:GridViewDataColumn>`. 

Width属性导致问题。如果我删除它然后它的工作原理。但我需要宽度,不知道为什么以及如何?