using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Markup;
namespace UWP.Converters
{
///
/// This class converts a boolean value into an other object.
/// Can be used to convert true/false to visibility, a couple of colors, couple of images, etc.
///
public class BoolToObjectConverter : IValueConverter
{
///
/// Gets or sets the value to be returned when the boolean is true
///
public object TrueValue { get; set; }
///
/// Gets or sets the value to be returned when the boolean is false
///
public object FalseValue { get; set; }
///
/// Convert a boolean value to an other object.
///
/// The source data being passed to the target.
/// The type of the target property, as a type reference.
/// An optional parameter to be used to invert the converter logic.
/// The language of the conversion.
/// The value to be passed to the target dependency property.
public object Convert(object value, Type targetType, object parameter, string language)
{
bool boolValue = value is bool && (bool)value;
// Negate if needed
if (TryParseBool(parameter))
{
boolValue = !boolValue;
}
return Convert(boolValue ? TrueValue : FalseValue, targetType);
}
///
/// Convert back the value to a boolean
///
/// If the parameter is a reference type, must match its reference to return true.
/// The target data being passed to the source.
/// The type of the target property, as a type reference (System.Type for Microsoft .NET, a TypeName helper struct for Visual C++ component extensions (C++/CX)).
/// An optional parameter to be used to invert the converter logic.
/// The language of the conversion.
/// The value to be passed to the source object.
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
bool result = Equals(value, Convert(TrueValue, targetType));
if (TryParseBool(parameter))
{
result = !result;
}
return result;
}
///
/// Helper method to safely cast an object to a boolean
///
/// Parameter to cast to a boolean
/// Bool value or false if cast failed
private bool TryParseBool(object parameter)
{
var parsed = false;
if (parameter != null)
{
bool.TryParse(parameter.ToString(), out parsed);
}
return parsed;
}
///
/// Helper method to convert a value from a source type to a target type.
///
/// The value to convert
/// The target type
/// The converted value
internal static object Convert(object value, Type targetType)
{
if (targetType.IsInstanceOfType(value))
{
return value;
}
else
{
return XamlBindingHelper.ConvertValue(targetType, value);
}
}
}
}