c# WPF TextBox 按索引检索行时的错误? [英] c# WPF TextBox bug when retrieve lines by index?

查看:34
本文介绍了c# WPF TextBox 按索引检索行时的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Simple wpf app here:

MainWindow.xaml:

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(省略使用)

MainWindow.cs (omitting using)

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!".

Run. Click "Fire 1!", then "Fire 2!".

预期结果:

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

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

但获得:

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

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 上检查.有什么解决方法吗?

Checked on MSVS 2017, .net 4.6.1, .net 4.6, .net 4.5.2, .net 4.5, .net 4. Any workarounds?

推荐答案

有什么解决方法吗?

Any workarounds?

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

You could get the lines from the string returned from the Text property:

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 按索引检索行时的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆