문제

If you were to parse 300 bytes of raw data 20 times a second into a bunch of WPF control properties, what would your solution be?

More specifically, I have a Modbus-enabled PLC and I need to make a WPF HMI for controlling it. Modbus is a communications protocol which requires polling for data changes. In contrast, WPF and .NET Framework in general promote event-driven model, so pushing data 20 times a second directly into controls seems unnatural to me. Not only does Modbus lack means of reporting data changes but also it doesn't provide high level representation of bytes, and it's up to developer to properly dissect an array of unsigned shorts into something meaningful.

While parsing such data is no big deal for me, coming up with a proper conversion to a bunch of event-enabled DependencyProperties (data binding assumed) is challenging. I wouldn't like to have a lot of initialization code or temporary storage to monitor changes.

도움이 되었습니까?

해결책

It won't be necessary to put your cyclically polled data into dependency properties. Such data properties will only be used as source of bindings, so it would be sufficient to have them in a class that implements INotifyPropertyChanged.

I would suggest to collect data of about 10 polling cycles and update the data properties no more than two times per second. You will certainly poll in a seperate thread, so you should make sure that you invoke the PropertyChanged event on the UI thread by Dispatcher.BeginInvoke like in the code below:

public class DataCollector : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private byte[] someData;

    public byte[] SomeData
    {
        get { return someData; }
        set
        {
            someData = value;

            if (PropertyChanged != null)
            {
                Application.Current.Dispatcher.BeginInvoke(PropertyChanged, this, new PropertyChangingEventArgs("SomeData"));
            }
        }
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top