Browse Source

Add new EnumToBooleanConverter

pull/8215/head
robloo 4 years ago
parent
commit
53a08f1263
  1. 57
      src/Avalonia.Controls/Converters/EnumToBooleanConverter.cs
  2. 12
      src/Avalonia.Controls/Converters/EnumValueEqualsConverter.cs

57
src/Avalonia.Controls/Converters/EnumToBooleanConverter.cs

@ -0,0 +1,57 @@
using System;
using System.Globalization;
using Avalonia.Data;
using Avalonia.Data.Converters;
namespace Avalonia.Controls.Converters
{
/// <summary>
/// Converter to convert an enum value to bool by comparing to the given parameter.
/// Both value and parameter must be of the same enum type.
/// </summary>
/// <remarks>
/// This converter is useful to enable binding of radio buttons with a selected enum value.
/// </remarks>
public class EnumToBooleanConverter : IValueConverter
{
/// <inheritdoc/>
public object? Convert(
object? value,
Type targetType,
object? parameter,
CultureInfo culture)
{
if (value == null &&
parameter == null)
{
return true;
}
else if (value == null ||
parameter == null)
{
return false;
}
else
{
return value!.Equals(parameter);
}
}
/// <inheritdoc/>
public object? ConvertBack(
object? value,
Type targetType,
object? parameter,
CultureInfo culture)
{
if (value is bool boolValue)
{
return boolValue ? parameter : BindingOperations.DoNothing;
}
else
{
return BindingOperations.DoNothing;
}
}
}
}

12
src/Avalonia.Controls/Converters/EnumValueEqualsConverter.cs

@ -10,7 +10,11 @@ namespace Avalonia.Controls.Converters
public class EnumValueEqualsConverter : IValueConverter
{
/// <inheritdoc/>
public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
public object? Convert(
object? value,
Type targetType,
object? parameter,
CultureInfo culture)
{
// Note: Unlike string comparisons, null/empty is not supported
// Both 'value' and 'parameter' must exist and if both are missing they are not considered equal
@ -46,7 +50,11 @@ namespace Avalonia.Controls.Converters
}
/// <inheritdoc/>
public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
public object? ConvertBack(
object? value,
Type targetType,
object? parameter,
CultureInfo culture)
{
throw new System.NotImplementedException();
}

Loading…
Cancel
Save