Winform窗体控件双向绑定数据模拟读写PLC数据

1.用Modbus工具模拟PLC

2.创建一个实体类

点击查看代码
internal class Data : INotifyPropertyChanged
{
    ushort[] ushorts = new ushort[10];
    public ushort D0 { get => ushorts[0]; set { ushorts[0] = value; OnPropertyChanged(nameof(D0)); } }
    public ushort D1 { get => ushorts[1]; set { ushorts[1] = value; } }
    public ushort D2 { get => ushorts[2]; set { ushorts[2] = value; } }
    public ushort D3 { get => ushorts[3]; set { ushorts[3] = value; } }
    public ushort D4 { get => ushorts[4]; set { ushorts[4] = value; } }
    public ushort D5 { get => ushorts[5]; set { ushorts[5] = value; } }
    public ushort D6 { get => ushorts[6]; set { ushorts[6] = value; } }
    public ushort D7 { get => ushorts[7]; set { ushorts[7] = value; } }
    public ushort D8 { get => ushorts[8]; set { ushorts[8] = value; } }
    public ushort D9 { get => ushorts[9]; set { ushorts[9] = value; } }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
3.创建窗体,添加10个TextBox控件用于显示和设置plc端数据

4.把数据绑定控件,利用定时器事件读取和写入PLC数据。

点击查看代码
        Data DB = new Data();
        ModbusTcp ModbusTcp = new ModbusTcp();
        private void Form1_Load(object sender, EventArgs e)
        {
            
            try
            {
                textBox1.DataBindings.Add("Text", DB, "D0");
                textBox2.DataBindings.Add("Text", DB, "D1");
                textBox3.DataBindings.Add("Text", DB, "D2");
                textBox4.DataBindings.Add("Text", DB, "D3");
                textBox5.DataBindings.Add("Text", DB, "D4");
                textBox6.DataBindings.Add("Text", DB, "D5");
                textBox7.DataBindings.Add("Text", DB, "D6");
                textBox8.DataBindings.Add("Text", DB, "D7");
                textBox9.DataBindings.Add("Text", DB, "D8");
                textBox10.DataBindings.Add("Text", DB, "D9");
                ModbusTcp.ModbusTcpConnect("127.0.0.1", 502);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            ushort[] ushorts = {DB.D0,DB.D1,DB.D2,DB.D3,DB.D4,DB.D5,DB.D6,DB.D7,DB.D8,DB.D9};
            ModbusTcp.WriteMultipleRegisters(1, 0, ushorts);

            ushorts = ModbusTcp.ReadHoldingRegisters(1, 0, 10);
            
        }

posted @ 2024-12-02 16:05  小卡拉咪  阅读(2)  评论(0编辑  收藏  举报