Hi i wanna still receiving 6 bytes from Serial Port only when is selected TabItem1.
And set checkboxes states depends on that bytes…
Example: but it not working :/
private void receiveData()
{
for(int i = 0; i < 3; ++i)
inputs[i] = serialPort.ReadByte();
for (int i = 0; i < 3; ++i)
outputs[i] = serialPort.ReadByte();
checkBoxI1.IsChecked = inputs[0] == 32 ? true : false;
checkBoxI2.IsChecked = inputs[1] == 32 ? true : false;
checkBoxI3.IsChecked = inputs[2] == 32 ? true : false;
checkBoxQ1.IsChecked = outputs[0] == 32 ? true : false;
checkBoxQ2.IsChecked = outputs[1] == 32 ? true : false;
checkBoxQ3.IsChecked = outputs[2] == 32 ? true : false;
}
// Tab change
private void tabControl1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (tabControl1.SelectedItem == tabItem1)
{
serialPort.Close();
try
{
receiveThread.Abort();
}
catch (NullReferenceException)
{
}
}
else if (tabControl1.SelectedItem == tabItem2)
{
serialPort.Open();
receiveThread = new Thread(receiveData);
receiveThread.Start();
}
}
I think the
receiveDatafunction is bound to theSerialPort.DataReceivedevent. This will in fact run on a different thread than your gui. And you like to change something on your gui which leads to the shown problem.To let this work you should maybe call
This will switch back to the gui thread to make these changes and the exception should be gone.