I'm using WPF and an MVVM architecture. I need to update my view and data model with any serial data that is received, which could be at any time.
To implement this I have
public static partial class SerialPortService
{
    private static SerialPort Port = new SerialPort
    {
        Handshake = Handshake.None,
        BaudRate = 9600,
        ReadTimeout = 400,
        DiscardNull = false,
        ReceivedBytesThreshold = 1,
        WriteTimeout = 100
    };
    public static string PortName
    {
        get => Port.PortName;
        set => Port.PortName = value;
    }
    public static SerialDataReceivedEventHandler DataReceived
    {
        set => Port.DataReceived += value;
    }
    public static void OpenCOMPort()
    {
        try
        {
            Port.Open();
            Port.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
        }
        catch(Exception ex)
        {
            Debug.Print("Exception caught while opening " + Port.PortName + Environment.NewLine + ex.ToString());
        }   
    }
    public static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        Byte[] rx_buffer = new Byte[ReadLength];    // ReadLength is set elsewhere
        try
        {
            for (int i = 0; i < ReadLength; i++)
            {
                rx_buffer[i] = (Byte)Port.ReadByte();
            }
            // update the viewModel with the data in rx_buffer here?!
        }
        catch(Exception ex)
        {
            if (Port.IsOpen)
            {
                Port.ReadExisting();        // Clears input buffer
            }
            Debug.Print(ex.ToString());
        }
    }
Whenever I receive data via the DataReceivedHandler(), I want to inform the viewModel that there is new data to display and to store it in my model (which is just the bytes received and a colour associated with the value of the first byte).
What is the best way to communicate this to the viewModel?
I also tried to update the model directly from the SerialPortService class but I got an error relating to thread affinity.
Thanks!
 
    