C#-覆盖/更新TextBlock中的文本 [英] C# - Overwrite / Update text in TextBlock

查看:571
本文介绍了C#-覆盖/更新TextBlock中的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在构建一个WPF应用程序,该应用程序使用SerialPort连接从Arduino接收并显示数据.我设法使实时数据在接收时显示出来,但是当文本到达TextBlock的底部时,文本停止.我想用传入的新数据替换旧值.这可能吗?

I am currently building a WPF application that receives and displays data from an Arduino using a SerialPort connection. I have managed to get the live data to display as it is received, however when the text reaches the bottom of the TextBlock the text stops. I would like to replace the old values with the new data coming in. Is this possible?

这是我的代码

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 =

编辑以回复评论

您可能要使用 ReadLine ,但请确保使用该问题的答复.

You might want to use ReadLine instead, but make sure to set the newline character with SerialPort.NewLine. See also this question's replies.

这篇关于C#-覆盖/更新TextBlock中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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