ValueConverterTests.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using System.Globalization;
  3. using Avalonia.Controls;
  4. using Avalonia.Data;
  5. using Avalonia.Data.Converters;
  6. using Avalonia.UnitTests;
  7. using Xunit;
  8. namespace Avalonia.Markup.Xaml.UnitTests.Converters
  9. {
  10. public class ValueConverterTests : XamlTestBase
  11. {
  12. [Fact]
  13. public void ValueConverter_Special_Values_Work()
  14. {
  15. using (UnitTestApplication.Start(TestServices.StyledWindow))
  16. {
  17. var xaml = @"
  18. <Window xmlns='https://github.com/avaloniaui'
  19. xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
  20. xmlns:c='clr-namespace:Avalonia.Markup.Xaml.UnitTests.Converters;assembly=Avalonia.Markup.Xaml.UnitTests'>
  21. <TextBlock Name='textBlock' Text='{Binding Converter={x:Static c:TestConverter.Instance}, FallbackValue=bar}'/>
  22. </Window>";
  23. var window = (Window)AvaloniaRuntimeXamlLoader.Load(xaml);
  24. var textBlock = window.FindControl<TextBlock>("textBlock");
  25. window.ApplyTemplate();
  26. window.DataContext = 2;
  27. Assert.Equal("foo", textBlock.Text);
  28. window.DataContext = -3;
  29. Assert.Equal("foo", textBlock.Text);
  30. window.DataContext = 0;
  31. Assert.Equal("bar", textBlock.Text);
  32. }
  33. }
  34. }
  35. public class TestConverter : IValueConverter
  36. {
  37. public static readonly TestConverter Instance = new TestConverter();
  38. public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  39. {
  40. if (value is int i)
  41. {
  42. if (i > 0)
  43. {
  44. return "foo";
  45. }
  46. if (i == 0)
  47. {
  48. return AvaloniaProperty.UnsetValue;
  49. }
  50. return BindingOperations.DoNothing;
  51. }
  52. return "(default)";
  53. }
  54. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  55. {
  56. throw new NotImplementedException();
  57. }
  58. }
  59. }