WPF上位机 - 实现TIA Wincc中的输入输出域

在TIA Wincc中输入输出域可以显示PLC中的变量,同时可以改变PLC中的变量,而在上位机中,使用多线程实时读取数据,在输入数据的时候可能PLC数据改变使得上位机数据同时改变。
所以需要在文本框获取到焦点的时候断开绑定,失去焦点的时候重新绑定数据。

// view 代码
                <TextBox
                    Width="100"
                    Margin="5,0,5,0"
                    Text="{Binding InternalAxis.Velocity}">
                    <behaviors:Interaction.Triggers>
                        <behaviors:EventTrigger EventName="GotFocus">
                            <behaviors:InvokeCommandAction Command="{Binding VelocityFoucsCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=TextBox}}" />
                        </behaviors:EventTrigger>
                        <behaviors:EventTrigger EventName="LostFocus">
                            <behaviors:InvokeCommandAction Command="{Binding VelocityChangedCommand}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=TextBox}}" />
                        </behaviors:EventTrigger>
                    </behaviors:Interaction.Triggers>
                </TextBox>
// vm代码
        private void TargetValueFocus(TextBox control, string property)
        {
            Binding binding = new Binding(property);
            binding.Mode = BindingMode.OneWay;
            if(control != null)
            {
                control.SetBinding(TextBox.TextProperty, binding);
            }
        }

        private void TargetValueChange(TextBox control, string property, int startByteAdr)
        {
            Binding binding = new Binding(property);
            binding.Mode = BindingMode.TwoWay;

            var value = Convert.ToDouble(control.Text);

            SiemensPlc.Instance.AxisController.Write(DataType.DataBlock, SiemensPlc.Instance.InterfaceDB, startByteAdr, value);

            control.SetBinding(TextBox.TextProperty, binding);
        }

        [RelayCommand]
        private void VelocityFoucs(object o)
        {
            var control = o as TextBox;

            TargetValueFocus(control, "InternalAxis.Velocity");
        }
        [RelayCommand]
        private void VelocityChanged(object o)
        {
            var startByteAdrMode = (AxisId * 730) + 130;
            var control = o as TextBox;

            TargetValueChange(control, "InternalAxis.Velocity", startByteAdrMode);
        }
posted @ 2024-05-06 19:27  4LPH4_αX  阅读(55)  评论(0编辑  收藏  举报