From a45ff34249978a3c0d9e7b37ba5c143f6764c703 Mon Sep 17 00:00:00 2001 From: Ionite Date: Thu, 7 Dec 2023 17:38:52 -0500 Subject: [PATCH] Add TernaryExtension --- .../MarkupExtensions/TernaryExtension.cs | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 StabilityMatrix.Avalonia/MarkupExtensions/TernaryExtension.cs diff --git a/StabilityMatrix.Avalonia/MarkupExtensions/TernaryExtension.cs b/StabilityMatrix.Avalonia/MarkupExtensions/TernaryExtension.cs new file mode 100644 index 00000000..2654cccc --- /dev/null +++ b/StabilityMatrix.Avalonia/MarkupExtensions/TernaryExtension.cs @@ -0,0 +1,42 @@ +using System; +using System.Globalization; +using Avalonia.Data; +using Avalonia.Data.Converters; +using Avalonia.Markup.Xaml; +using Avalonia.Markup.Xaml.MarkupExtensions; + +namespace StabilityMatrix.Avalonia.MarkupExtensions; + +/// +/// https://github.com/AvaloniaUI/Avalonia/discussions/7408 +/// +/// +/// {e:Ternary SomeProperty, True=1, False=0} +/// +public class TernaryExtension : MarkupExtension +{ + public string Path { get; set; } + + public Type Type { get; set; } + + public object? True { get; set; } + + public object? False { get; set; } + + public override object ProvideValue(IServiceProvider serviceProvider) + { + var cultureInfo = CultureInfo.GetCultureInfo("en-US"); + var binding = new ReflectionBindingExtension(Path) + { + Mode = BindingMode.OneWay, + Converter = new FuncValueConverter( + isTrue => + isTrue + ? Convert.ChangeType(True, Type, cultureInfo.NumberFormat) + : Convert.ChangeType(False, Type, cultureInfo.NumberFormat) + ) + }; + + return binding.ProvideValue(serviceProvider); + } +}