MultiBindingTests_Converters.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 System.Text;
  8. using Avalonia.Controls;
  9. using Avalonia.Data;
  10. using Avalonia.Data.Converters;
  11. using Avalonia.Data.Core;
  12. using Xunit;
  13. namespace Avalonia.Markup.UnitTests.Data
  14. {
  15. public class MultiBindingTests_Converters
  16. {
  17. [Fact]
  18. public void StringFormat_Should_Be_Applied()
  19. {
  20. var textBlock = new TextBlock
  21. {
  22. DataContext = new MultiBindingTests_Converters.Class1(),
  23. };
  24. var target = new MultiBinding
  25. {
  26. StringFormat = "Foo + Bar = {0}",
  27. Converter = new SumOfDoublesConverter(),
  28. Bindings =
  29. {
  30. new Binding(nameof(MultiBindingTests_Converters.Class1.Foo)),
  31. new Binding(nameof(MultiBindingTests_Converters.Class1.Bar)),
  32. }
  33. };
  34. textBlock.Bind(TextBlock.TextProperty, target);
  35. Assert.Equal("Foo + Bar = 3", textBlock.Text);
  36. }
  37. [Fact]
  38. public void StringFormat_Should_Not_Be_Applied_When_Binding_To_Non_String_Or_Object()
  39. {
  40. var textBlock = new TextBlock
  41. {
  42. DataContext = new MultiBindingTests_Converters.Class1(),
  43. };
  44. var target = new MultiBinding
  45. {
  46. StringFormat = "Hello {0}",
  47. Converter = new SumOfDoublesConverter(),
  48. Bindings =
  49. {
  50. new Binding(nameof(MultiBindingTests_Converters.Class1.Foo)),
  51. new Binding(nameof(MultiBindingTests_Converters.Class1.Bar)),
  52. }
  53. };
  54. textBlock.Bind(TextBlock.WidthProperty, target);
  55. Assert.Equal(3.0, textBlock.Width);
  56. }
  57. private class SumOfDoublesConverter : IMultiValueConverter
  58. {
  59. public object Convert(IList<object> values, Type targetType, object parameter, CultureInfo culture)
  60. {
  61. return values.OfType<double>().Sum();
  62. }
  63. }
  64. private class Class1
  65. {
  66. public double Foo { get; set; } = 1;
  67. public double Bar { get; set; } = 2;
  68. }
  69. }
  70. }