68 lines
3 KiB
C#
68 lines
3 KiB
C#
using System;
|
|
using System.Windows.Data;
|
|
|
|
namespace JD.WPF.Converters
|
|
{
|
|
/// <summary>
|
|
/// Base implementation for a TextBox converter.
|
|
/// This converter is built to support the recent binding changes introduced by .NET 4.0
|
|
/// (see http://stackoverflow.com/questions/4712917/why-does-binding-setup-behave-differently-in-net-4-vs-net-3-5).
|
|
/// </summary>
|
|
public abstract class TextBoxConverterBase<TypeFrom, TypeTo> : IValueConverter
|
|
{
|
|
private TypeFrom m_originalValue;
|
|
|
|
protected bool m_hasOriginalValue;
|
|
|
|
public bool RestoreOriginalValueIfIdentical { get; set; } = true;
|
|
|
|
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
|
|
{
|
|
if (!(value is TypeTo) || targetType != typeof(TypeFrom))
|
|
throw new NotSupportedException($"This converter only accepts conversions from {typeof(TypeTo).Name} to {typeof(TypeFrom).Name}");
|
|
|
|
TypeTo sourceValue = (TypeTo)value;
|
|
TypeFrom targetValue;
|
|
if (!Convert(sourceValue, out targetValue, parameter, culture))
|
|
throw new InvalidOperationException("Binding operation failed. ");
|
|
|
|
if (RestoreOriginalValueIfIdentical)
|
|
{
|
|
if (HasOriginalValue(parameter))
|
|
{
|
|
m_hasOriginalValue = false;
|
|
if (AreValuesIdentical(GetOriginalValue(parameter), sourceValue, targetValue, parameter))
|
|
return Binding.DoNothing;
|
|
}
|
|
}
|
|
|
|
return targetValue;
|
|
}
|
|
|
|
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
|
|
{
|
|
if (!(value is TypeFrom) || targetType != typeof(TypeTo))
|
|
throw new NotSupportedException($"This converter only accepts conversions from {typeof(TypeFrom).Name} to {typeof(TypeTo).Name}");
|
|
|
|
TypeFrom sourceValue = (TypeFrom)value;
|
|
TypeTo targetValue;
|
|
if (!ConvertBack(sourceValue, out targetValue, parameter, culture))
|
|
throw new InvalidOperationException("Binding operation failed. ");
|
|
|
|
if (RestoreOriginalValueIfIdentical)
|
|
{
|
|
m_hasOriginalValue = true;
|
|
m_originalValue = sourceValue;
|
|
}
|
|
|
|
return targetValue;
|
|
}
|
|
|
|
public abstract bool Convert(TypeTo sourceValue, out TypeFrom targetValue, object parameter, System.Globalization.CultureInfo culture);
|
|
public abstract bool ConvertBack(TypeFrom sourceValue, out TypeTo targetValue, object parameter, System.Globalization.CultureInfo culture);
|
|
public abstract bool AreValuesIdentical(TypeFrom originalValue, TypeTo sourceValue, TypeFrom targetValue, object parameter);
|
|
|
|
protected virtual bool HasOriginalValue(object parameter) { return m_hasOriginalValue; }
|
|
protected virtual TypeFrom GetOriginalValue(object parameter) { return m_originalValue; }
|
|
}
|
|
}
|