首页 > 解决方案 > RichTextBox_logs.AppendText(Environment.NewLine); 返回两条新线?

问题描述

我不知道为什么,但它总是输入两个新行:

在此处输入图像描述

private void getMyIPAddress()
{
    String Address = "";
    this.Dispatcher.Invoke(() =>
    {
        this.RichTextBox_logs.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
    });
    while (true)
    {
        this.Dispatcher.Invoke(() =>
        {
            this.RichTextBox_logs.AppendText(Environment.NewLine);
            
            //this.RichTextBox_logs.ScrollToEnd();
        });
        WebRequest request = WebRequest.Create("http://checkip.dyndns.com/");
        try
        {
            using (WebResponse response = request.GetResponse())
            {
                using (StreamReader stream = new StreamReader(response.GetResponseStream()))
                {
                    Address = stream.ReadToEnd();
                }
                int first = Address.IndexOf("Address: ") + 9;
                int last = Address.IndexOf("</body>");               

                if (CurrentAddressHolder != Address.Substring(first, last - first))
                {
                    CurrentAddressHolder = Address.Substring(first, last - first);

                    this.Dispatcher.Invoke(() =>
                    {
                        this.textBox_ip.Text = CurrentAddressHolder;
                    });
                    
                }

                this.Dispatcher.Invoke(() =>
                {
                    this.RichTextBox_logs.AppendText("IP is " + CurrentAddressHolder);
                });
            }
        }
        catch(Exception e)
        {
            this.Dispatcher.Invoke(() =>
            {
                this.RichTextBox_logs.AppendText(e.ToString());
            });
        }
    }
}

我是多线程的新手,我不确定它是否会影响新行的语法。

非常欢迎任何输入或代码修订/改进。谢谢。

标签: c#wpfmultithreadingrichtextbox

解决方案


好像你的问题是行距。

解决方案一:

代替该AppendText()方法,使用以下方法将文本行添加到RichTextBox

public void AddText(RichTextBox rtb, string message, double spacing = 4)
{
    var paragraph = new Paragraph() { LineHeight = spacing };
    paragraph.Inlines.Add(new Run(message));
    rtb.Document.Blocks.Add(paragraph);
}

使用此方法,您将能够通过设置 LineHeight 值以编程方式更改段落之间的行距。

使用这种方法时不需要添加Environment.NewLine. 每个块(段落)将自动格式化为不同的行。

解决方案二:

尝试更改段落边距(请参阅以下帖子https://stackoverflow.com/a/445897/6630084):

<RichTextBox x:Name="RichTextBox_logs" >
    <RichTextBox.Resources>
        <Style TargetType="{x:Type Paragraph}">
            <Setter Property="Margin" Value="0"/>
        </Style>
    </RichTextBox.Resources>
    ...
<RichTextBox>

推荐阅读