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

标签 c# wpf textbox

这里是简单的 wpf 应用程序:

主窗口.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();
    }
}

运行。点击“开火 1!”,然后点击“开火 2!”。

预期结果:

150 300 450 600 750 900 15000 30000 45000 60000 75000 90000

但获得:

150 300 450 600 750 900 15001 30002 45003 60004 75004 90005

检查 MSVS 2017、.net 4.6.1、.net 4.6、.net 4.5.2、.net 4.5、.net 4。 有什么解决方法吗?

最佳答案

Any workarounds?

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

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();
}

关于c# WPF TextBox 按索引检索行时出现错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51788009/

相关文章:

c# - GetHashCode 扩展方法

c# - WPF C# LINQ : Operator '&&' cannot be applied to operands of type 'string' and 'string' query

C#WPF Textblock每行不同的字体颜色

c# - 是否可以更改 ToolStripMenuItem 工具提示字体?

c# - 将事件从 C 类通过 B 类传递到 A 类

c# - UWP 从 WPF 应用程序启动我的应用程序

c# - 如何将 textbox.text 转换为 int 或仅用于 int 输入的内容?

c# - 在文本框中的鼠标位置放置文本

javascript - jQuery 选择器中的括号

c# - Active Directory,枚举用户组,COM 异常