C#-覆盖/更新文本块中的文本
我目前正在构建一个WPF应用程序,它使用串口连接从Arduino接收和显示数据。我已经设法让实时数据在接收时显示出来,但是当文本到达文本块的底部时,文本就会停止。我想用新数据替换旧值。这可能吗 这是我的密码C#-覆盖/更新文本块中的文本,c#,wpf,arduino,C#,Wpf,Arduino,我目前正在构建一个WPF应用程序,它使用串口连接从Arduino接收和显示数据。我已经设法让实时数据在接收时显示出来,但是当文本到达文本块的底部时,文本就会停止。我想用新数据替换旧值。这可能吗 这是我的密码 public partial class MainWindow : Window { SerialPort sp = new SerialPort(); public MainWindow() { InitializeComp
public partial class MainWindow : Window
{
SerialPort sp = new SerialPort();
public MainWindow()
{
InitializeComponent();
}
private void btnCon_Click(object sender, RoutedEventArgs e)
{
try
{
String portname = txtCom.Text;
sp.PortName = portname;
sp.BaudRate = 9600;
sp.DtrEnable = true;
sp.Open();
sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
txbStatus.Text = "Connected";
}
catch (Exception)
{
MessageBox.Show("Please enter a valid port number");
}
}
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
this.Dispatcher.Invoke(() =>
{
SerialPort sp = (SerialPort)sender;
txbStatus.Text += sp.ReadExisting(); //Displaying data in TextBlock
});
}
谢谢换衣服就行了
txbStatus.Text +=
到
根据评论进行编辑
您可能想改为使用,但请确保将换行符设置为。另请参见。实现这一点的廉价方法是替换此:
txbStatus.Text += sp.ReadExisting(); //Displaying data in TextBlock
为此:
if (txbStatus.Text.Length > MAGIC_NUMBER)
{
txbStatus.Text = sp.ReadExisting(); //Replace existing content
}
else
{
txbStatus.Text += sp.ReadExisting(); //Append content
}
这会将文本追加到某一点,如果太长,则替换它
您必须根据文本区域的大小、字体大小、数据量、可用性等,通过反复试验,得出MAGIC_NUMBER
另一种方法:
var oldText = txbStatus.Text;
var newText = sp.ReadExisting();
var combinedText = oldText + newText;
var shortenedText = combinedText.Substring(combinedText.Length - MAXIMUM_LENGTH);
txbStatus.Text = shortenedText;
这将强制文本在
最大长度处截断,只保留最新文本。谢谢您的回答。它确实替换了输入的值,但是现在它在接收到整个值之前替换了数据。例如,635现在显示为6或56。任何解决我的问题的建议。@inspiro,现在都非常有效。感谢您的帮助,在替换值时,这部分解决了问题。但是我仍然有一个小问题,当你从四位数切换到一位数时,数值出现在不同的行上。将ReadExisting更改为ReadLine并删除+解决了此问题。谢谢
var oldText = txbStatus.Text;
var newText = sp.ReadExisting();
var combinedText = oldText + newText;
var shortenedText = combinedText.Substring(combinedText.Length - MAXIMUM_LENGTH);
txbStatus.Text = shortenedText;