我目前正在开发一个通过SerialPort
类与外部设备通信的类,但我需要根据设备发回的消息更新UI。
我尝试了以下代码,但它不起作用:
using System.IO.Ports;
namespace LearningSteps
{
/// <summary>
/// Interaction logic for Comm.xaml
/// </summary>
///
public class Teste
{
private SerialPort _myPort;
public Teste(SerialPort P) { _myPort = P; }
public void Funcao(SerialDataReceivedEventHandler H)
{
_myPort.DataReceived += H;
byte[] vetor = new byte[] { 0x24, 0x24, 0xCF, 0x00, 0x01, 0x02, 0x25, 0x33, 0x7E };
_myPort.Write(vetor, 0, 9);
}
}
public partial class Comm : Window
{
SerialPort port;
Teste T;
public delegate void AtualizaCallBack(string message);
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
public Comm()
{
InitializeComponent();
port = new SerialPort("COM5",115200,Parity.None,8,StopBits.One);
port.RtsEnable = false;
port.DtrEnable = false;
port.Handshake = Handshake.None;
port.NewLine = "~";
port.Open();
T = new Teste(port);
}
private void Recebido(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
String indata = sp.ReadExisting();
my_label.Dispatcher.Invoke(new AtualizaCallBack(this.atualiza),new object[]{indata});
}
private void bt_Click(object sender, RoutedEventArgs e)
{
T.Funcao(Recebido);
}
private void atualiza(string s)
{
byte[] vet = encoding.GetBytes(s);
my_label.Content = BitConverter.ToString(vet);
}
}
}
我尝试编译时遇到错误,我认为是因为我正在尝试发送内部SerialDataReceivedEventHandler
作为参数。但我不知道如何使用T.Funcao
并更新我的UI。
错误说: “PresentationFramework.dll中发生了'System.Window.Markup.XamlParseException'类型的未处理异常
附加信息:'与指定的绑定约束匹配的构造函数类型'LearningSteps.Comm'的调用引发了异常。行号“3”和行位置“9”。
如果存在此异常的处理程序,则可以安全地继续该程序。“
有人可以帮帮我吗?