WPF上位机 - 使用转换器实现TIA Wincc中的可见性和外观功能

在TIA Wincc 中有这样的功能,使用True or false 控制控件的可见性或者外观的情况。

在上位机中需要使用转换器这样对True or false 值转换为 需要的笔刷或者Visible属性。

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Media;

namespace SiemensAxisControl.Model.Converter
{
    public class BoolToBrushConverter : IValueConverter
    {
        public object Convert(object value , Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null && bool.Parse(value.ToString()))
            {
                return new SolidColorBrush(Color.FromRgb(0,255,0));
            }
            return Brushes.White;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

还有一种情况,不是True or false 的布尔值,而是根据整形值的情况改变控件的可见性或者外观。
如在TIA中以下的情况

  • 变量值等于某一个值改变外观

  • 变量值在某一个区间内改变外观

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;

namespace SiemensAxisControl.Model.Converter
{
    internal class IntToBrushConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            // 尝试将参数解析为两个整数值,分别代表下限和上限
            if (parameter != null && parameter.ToString().Split('-').Length == 2 &&
                int.TryParse(parameter.ToString().Split('-')[0], out int lowerBound) &&
                int.TryParse(parameter.ToString().Split('-')[1], out int upperBound))
            {
                    // 检查传入的值是否在指定的范围内
                    if (value is short intValue &&  intValue >= lowerBound && intValue <= upperBound)
                    {
                        return new SolidColorBrush(Color.FromRgb(0, 255, 0)); ;
                    }
            }
            // 如果不满足条件,则默认为白色
            return Brushes.White;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
posted @ 2024-05-03 19:29  4LPH4_αX  阅读(91)  评论(0编辑  收藏  举报