Browse Source

Merge pull request #11313 from workgroupengineering/features/Issue_11311

feat: CompiledBinding StringFormat without curly braces
Max Katz 2 years ago
parent
commit
7e2150ec54

+ 6 - 1
src/Avalonia.Base/Data/Converters/StringFormatValueConverter.cs

@@ -35,7 +35,12 @@ namespace Avalonia.Data.Converters
         public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
         {
             value = Inner?.Convert(value, targetType, parameter, culture) ?? value;
-            return string.Format(culture, Format, value);
+            var format = Format!;
+            if (!format.Contains('{'))
+            {
+                format = $"{{0:{format}}}";
+            }
+            return string.Format(culture, format, value);
         }
 
         /// <inheritdoc/>

+ 31 - 2
tests/Avalonia.Markup.Xaml.UnitTests/MarkupExtensions/CompiledBindingExtensionTests.cs

@@ -1795,7 +1795,33 @@ namespace Avalonia.Markup.Xaml.UnitTests.MarkupExtensions
                 Assert.Equal(123, comboBox.SelectedItem);
             }
         }
-        
+
+        [Theory]
+        [InlineData(false)]
+        [InlineData(true)]
+        public void Should_Use_StringFormat_Without_Braces(bool compileBindings)
+        {
+            using (UnitTestApplication.Start(TestServices.StyledWindow))
+            {
+                var xaml = $@"
+<Window xmlns='https://github.com/avaloniaui'
+        xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
+        xmlns:local='clr-namespace:Avalonia.Markup.Xaml.UnitTests.MarkupExtensions;assembly=Avalonia.Markup.Xaml.UnitTests'
+        x:DataType='local:TestDataContext'
+        x:CompileBindings='{compileBindings}'>
+    <TextBlock Name='textBlock' Text='{{Binding DecimalValue, StringFormat=c2}}'/>
+</Window>";
+                var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
+                var textBlock = window.FindControl<TextBlock>("textBlock");
+
+                var dataContext = new TestDataContext();
+                window.DataContext = dataContext;
+
+                Assert.Equal(string.Format("{0:c2}", TestDataContext.ExpectedDecimal)
+                    , textBlock.GetValue(TextBlock.TextProperty));
+            }
+        }
+
         static void Throws(string type, Action cb)
         {
             try
@@ -1891,7 +1917,10 @@ namespace Avalonia.Markup.Xaml.UnitTests.MarkupExtensions
         public static string StaticProperty => "World";
 
         public ListItemCollectionView<int> GenericProperty { get; } = new();
-        
+
+        public const decimal ExpectedDecimal = 15.756m;
+        public decimal DecimalValue { get; set; } = ExpectedDecimal;
+
         public class NonIntegerIndexer : NotifyingBase, INonIntegerIndexerDerived
         {
             private readonly Dictionary<string, string> _storage = new Dictionary<string, string>();