按索引检索行时,c#WPF TextBox错误?

时间:2018-08-10 13:49:59

标签: c# wpf textbox

此处是简单的wpf应用程序:

MainWindow.xaml:

<Window x:Class="wpf_textbox_of.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:wpf_textbox_of"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="20"/>
            <RowDefinition Height="20"/>
        </Grid.RowDefinitions>
        <TextBox Grid.Row="0" Margin="5"  Name="txt" AcceptsReturn="True" AcceptsTab="True" />
        <Button Grid.Row="1" Content="Fire 1!" Click="btn_OnClick" />
        <Button Grid.Row="2" Content="Fire 2!" Click="btn2_OnClick" />
    </Grid>
</Window>

MainWindow.cs(省略使用)

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void btn_OnClick(object sender, RoutedEventArgs e)
    {
        var sb = new StringBuilder();
        for (int i = 0; i < 90009; i++)
            sb.AppendLine($"{i}");
        txt.Text = sb.ToString();
    }

    private void btn2_OnClick(object sender, RoutedEventArgs e)
    {
        var sb = new StringBuilder();
        for (var i = 1; i < 7; i++)
            sb.AppendLine(txt.GetLineText(150 * i).Trim());
        for (var i = 1; i < 7; i++)
            sb.AppendLine(txt.GetLineText(15000*i).Trim());
        txt.Text = sb.ToString();
    }
}

运行。单击“ Fire 1!”,然后单击“ Fire 2!”。

预期结果:

  

150300450600750900 15000 30000 45000 60000 75000 90000

但是获得:

  

150300450600750900 15001 30002 45003 60004 75004 90005

在MSVS 2017,.net 4.6.1,.net 4.6,.net 4.5.2,.net 4.5,.net 4。 有任何解决方法吗?

1 个答案:

答案 0 :(得分:0)

  

有什么解决方法吗?

您可以从string属性返回的Text获取行:

private void btn2_OnClick(object sender, RoutedEventArgs e)
{
    string[] lines = txt.Text.Split(new char[] { '\n' });
    var sb = new StringBuilder();
    for (var i = 1; i < 7; i++)
        sb.AppendLine(lines[150 * i].Trim());
    for (var i = 1; i < 7; i++)
        sb.AppendLine(lines[15000 * i].Trim());
    txt.Text = sb.ToString();
}