Browse Source

Added converter that uses functions, rather than having to override the class.

Kenric Nugteren 1 năm trước cách đây
mục cha
commit
317e6141e0
1 tập tin đã thay đổi với 34 bổ sung0 xóa
  1. 34 0
      inabox.wpf/Converters/FuncConverter.cs

+ 34 - 0
inabox.wpf/Converters/FuncConverter.cs

@@ -0,0 +1,34 @@
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using System.Windows.Data;
+
+namespace InABox.Wpf;
+
+public class FuncConverter<TIn, TOut>(Func<TIn, TOut> convert, Func<TOut, TIn>? convertBack) : IValueConverter
+{
+    public Func<TIn, TOut> ConvertFunc { get; set; } = convert;
+
+    public Func<TOut, TIn>? ConvertBackFunc { get; set; } = convertBack;
+
+    public object? Convert(object? value, Type targetType, object parameter, CultureInfo culture)
+    {
+        if(value is TIn tIn)
+        {
+            return ConvertFunc(tIn);
+        }
+        return null;
+    }
+
+    public object? ConvertBack(object? value, Type targetType, object parameter, CultureInfo culture)
+    {
+        if(value is TOut tOut && ConvertBackFunc is not null)
+        {
+            return ConvertBackFunc.Invoke(tOut);
+        }
+        return null;
+    }
+}