2017-08-16 51 views
1

我目前正在构建一个WPF应用程序,它使用SerialPort连接接收并显示来自Arduino的数据。我设法让实时数据在收到时显示,但是当文本到达TextBlock的底部时,文本停止。我想用新的数据替换旧的值。这可能吗?C# - 在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 
     }); 
    } 

感谢

回答

0

只要改变

txbStatus.Text += 

txbStatus.Text = 

编辑回应置评

您可能想用ReadLine代替,但一定要设置换行符SerialPort.NewLine。另见this question's replies

+0

感谢您的回答。这确实取代了输入的值,但是它在接收整个值之前正在替换数据。例如635现在显示为6或56.任何建议。 –

+0

@white_reece查看我编辑的答案。 – ispiro

+0

@inspiro解决了我的问题,现在完美地工作。感谢您的帮助 –

1

那么便宜的方式做这将是替换此:

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; 

这将强制文本在MAXIMUM_LENGTH截断,只保留最新的文本。

+0

随着值被替换,这部分解决了问题。但是,我仍然遇到一个小问题,当您从四位数字切换到一位数字时,这些值出现在不同的行上。将ReadExisting改为ReadLine并删除+解决了这个问题。谢谢 –