Bootstrap

WPF 字符串传值到后端

 public class CustormNode : UIElement
 {
     public ValueCollection Values { get; set; } = new ValueCollection();
 }

 [TypeConverter(typeof(ValueTypeConverter))]
 public class ValueCollection
 {
     private readonly List<int> _values = new List<int>();

     public int? this[int index]
     {
         get => _values.Count == 0 ? null : _values[index];
     }
     public void Append(int[] values)
     {
         _values.AddRange(values);
     }
 }


public class ValueTypeConverter : TypeConverter
 {
     public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType)
     {
         return sourceType == typeof(string);
     }

     public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value)
     {

         if (value == null || string.IsNullOrEmpty(value.ToString()))
             return base.ConvertFrom(context, culture, value);

         ValueCollection vc = new ValueCollection();
         string[] temp = value.ToString().Split(",");// new string[]{10,20,30}
         vc.Append(temp.Select(vs =>
         {
             int v = 0;
             int.TryParse(vs, out v);
             return v;
         }).ToArray());
         return vc;
     }
 }

ValueTypeConverter 类为 ValueCollection 提供了将字符串转换为 ValueCollection 的功能,尤其适用于处理形如 “10,20,30” 这样以逗号分隔的字符串,将其转换为存储这些数字的 ValueCollection 对象,方便在 UI 元素的数据绑定和序列化等场景中使用。

;