c# - 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());
});
}
}
}
我是多线程的新手,我不确定它是否会影响新行的语法。
非常欢迎任何输入或代码修订/改进。谢谢。
解决方案
好像你的问题是行距。
解决方案一:
代替该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>
推荐阅读
- visual-studio-code - “ApolloServer”类型上不存在属性“start”
- mysql - Hibernate:有没有办法在“Column xyz cannot be null”消息中显示表名?
- pandas - 如何根据图形按比例调整徽标的大小?
- swift - 如何将 Mac 上的 SwiftUI 菜单命令连接到模型
- javascript - 如何为chartjs散点图中的每个数据添加颜色
- python - 将 int 和 string 从字符串 python 拆分为元组
- openstack - Radosgateway 服务器(客户端)到 Haproxy(然后是后端 keystone 容器)为什么获取客户端请求所需的时间很高,例如 5 秒到 20 秒
- nginx - 当发出 GET 以外的请求时,如何清除或重置 nginx 缓存?
- sql - 简单的 SQL 任务
- javascript - firebase.auth().SignInWithPhoneNumber 不是函数