BoolToVisibilityConverterExtension.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System;
  2. using System.Globalization;
  3. using System.Windows;
  4. using System.Windows.Data;
  5. using System.Windows.Markup;
  6. namespace AIDiagnosisDemo.Extensions
  7. {
  8. [MarkupExtensionReturnType(typeof(IValueConverter))]
  9. public class BoolToVisibilityConverterExtension : MarkupExtension
  10. {
  11. [ThreadStatic]
  12. private static BoolToVisibilityConverter _converter;
  13. public override object ProvideValue(IServiceProvider serviceProvider)
  14. {
  15. return _converter ?? (_converter = new BoolToVisibilityConverter());
  16. }
  17. private class BoolToVisibilityConverter : IValueConverter
  18. {
  19. public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  20. {
  21. var converterParameter = parameter?.ToString();
  22. if (value == null)
  23. {
  24. return converterParameter == "Reverse" ? Visibility.Collapsed : Visibility.Visible;
  25. }
  26. if ((bool)value)
  27. {
  28. return converterParameter == "Reverse" ? Visibility.Collapsed : Visibility.Visible;
  29. }
  30. return converterParameter == "Reverse" ? Visibility.Visible : Visibility.Collapsed;
  31. }
  32. public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  33. {
  34. var converterParameter = parameter?.ToString();
  35. if (value == null)
  36. {
  37. return Visibility.Visible;
  38. }
  39. if ((Visibility)value == Visibility.Visible)
  40. {
  41. return converterParameter == "Reverse" ? false : true;
  42. }
  43. return converterParameter == "Reverse" ? true : false;
  44. }
  45. }
  46. }
  47. }