C# - 在TextBlock中覆盖/更新文本

时间:2017-08-16 18:59:00

标签: c# wpf arduino

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

这是我的代码

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
        });
    }

由于

2 个答案:

答案 0 :(得分:1)

这样做的便宜方法就是替换它:

NSClassFromString()

用这个:

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; 截断,只保留最新的文本。

答案 1 :(得分:0)

只需更改

txbStatus.Text +=

txbStatus.Text =

编辑以回应评论

您可能希望使用ReadLine,但请务必使用SerialPort.NewLine设置换行符。另请参阅this question's replies

相关问题