MultiBindingTests_Converters.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. // Copyright (c) The Avalonia Project. All rights reserved.
  2. // Licensed under the MIT license. See license.md file in the project root for full license information.
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.Linq;
  7. using Avalonia.Controls;
  8. using Avalonia.Data;
  9. using Avalonia.Data.Converters;
  10. using Avalonia.Layout;
  11. using Xunit;
  12. namespace Avalonia.Markup.UnitTests.Data
  13. {
  14. public class MultiBindingTests_Converters
  15. {
  16. [Fact]
  17. public void StringFormat_Should_Be_Applied()
  18. {
  19. var textBlock = new TextBlock
  20. {
  21. DataContext = new Class1(),
  22. };
  23. var format = "{0:0.0} + {1:00}";
  24. var target = new MultiBinding
  25. {
  26. StringFormat = format,
  27. Bindings =
  28. {
  29. new Binding(nameof(Class1.Foo)),
  30. new Binding(nameof(Class1.Bar)),
  31. }
  32. };
  33. textBlock.Bind(TextBlock.TextProperty, target);
  34. Assert.Equal(string.Format(format, 1, 2), textBlock.Text);
  35. }
  36. [Fact]
  37. public void StringFormat_Should_Be_Applied_After_Converter()
  38. {
  39. var textBlock = new TextBlock
  40. {
  41. DataContext = new Class1(),
  42. };
  43. var target = new MultiBinding
  44. {
  45. StringFormat = "Foo + Bar = {0}",
  46. Converter = new SumOfDoublesConverter(),
  47. Bindings =
  48. {
  49. new Binding(nameof(Class1.Foo)),
  50. new Binding(nameof(Class1.Bar)),
  51. }
  52. };
  53. textBlock.Bind(TextBlock.TextProperty, target);
  54. Assert.Equal("Foo + Bar = 3", textBlock.Text);
  55. }
  56. [Fact]
  57. public void StringFormat_Should_Not_Be_Applied_When_Binding_To_Non_String_Or_Object()
  58. {
  59. var textBlock = new TextBlock
  60. {
  61. DataContext = new Class1(),
  62. };
  63. var target = new MultiBinding
  64. {
  65. StringFormat = "Hello {0}",
  66. Converter = new SumOfDoublesConverter(),
  67. Bindings =
  68. {
  69. new Binding(nameof(Class1.Foo)),
  70. new Binding(nameof(Class1.Bar)),
  71. }
  72. };
  73. textBlock.Bind(Layoutable.WidthProperty, target);
  74. Assert.Equal(3.0, textBlock.Width);
  75. }
  76. private class SumOfDoublesConverter : IMultiValueConverter
  77. {
  78. public object Convert(IList<object> values, Type targetType, object parameter, CultureInfo culture)
  79. {
  80. return values.OfType<double>().Sum();
  81. }
  82. }
  83. private class Class1
  84. {
  85. public double Foo { get; set; } = 1;
  86. public double Bar { get; set; } = 2;
  87. }
  88. }
  89. }