C# - Overwrite / Update text in TextBlock

南笙酒味 提交于 2019-12-11 07:18:31

问题


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?

This is my code

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

Thanks


回答1:


Just change

txbStatus.Text +=

to

txbStatus.Text =

EDIT in response to comment

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




回答2:


Well the cheap way to do this would be to replace this:

txbStatus.Text += sp.ReadExisting(); //Displaying data in TextBlock

with this:

if (txbStatus.Text.Length > MAGIC_NUMBER) 
{
    txbStatus.Text = sp.ReadExisting(); //Replace existing content
}
else
{
    txbStatus.Text += sp.ReadExisting(); //Append content
}

This will append the text up to a certain point and replace it if it gets too long.

You will have to come up with MAGIC_NUMBER with trial and error based on the size of the text area, font size, volume of data, usability, etc.

Another approach:

var oldText = txbStatus.Text;
var newText = sp.ReadExisting();
var combinedText = oldText + newText;
var shortenedText = combinedText.Substring(combinedText.Length - MAXIMUM_LENGTH);
txbStatus.Text = shortenedText;

This will force the text to truncate at MAXIMUM_LENGTH, keeping only the newest of the text.



来源:https://stackoverflow.com/questions/45721074/c-sharp-overwrite-update-text-in-textblock

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!