从文本框中读取字符串

时间:2016-06-22 05:00:42

标签: c# wpf serial-port

我在WPF应用程序中有以下代码。 它从串口读取字符串并显示在文本框中。 我想根据串行输入执行操作。

我想通过读取字符串变量(RData)或阅读textbox.text来做。

我已尝试使用函数中的if语句,但它不起作用。请帮忙。

public partial class MainWindow : Window
{
    SerialPort serial = new SerialPort();
    string RData;

    public MainWindow()
    {
        InitializeComponent();
        getPorts();
    }

    void getPorts()
    {
        String[] ports = SerialPort.GetPortNames();
        comboBoxPorts.ItemsSource = ports;
    }

    private void buttonConnect_Click(object sender, RoutedEventArgs e)
    {
        serial.PortName = comboBoxPorts.Text;
        serial.BaudRate = 9600;
        serial.DataBits = 8;
        serial.Handshake = System.IO.Ports.Handshake.None;
        serial.StopBits = StopBits.One;
        serial.ReadTimeout = -1;
        serial.WriteTimeout = -1;
        serial.Open();

        if (serial.IsOpen)
        {
            buttonConnect.IsEnabled = false;
            labelConState.Content = "Connected";
            labelConState.Foreground = System.Windows.Media.Brushes.Green;

            serial.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(Recieve);
        }
    }

    private delegate void UpdateUiTextDelegate(string text);

    private void Recieve
        (object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {
        RData = serial.ReadExisting();

        Dispatcher.Invoke(DispatcherPriority.Send, new UpdateUiTextDelegate(WriteData), RData);
    }

    private void WriteData(string text)
    {
        textBoxPrompt.Text += text;
    }
}

1 个答案:

答案 0 :(得分:-1)

您应该设置SerialPort的奇偶校验属性。