using System;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;
namespace Developpez.Dotnet.Windows.Markup
{
///
/// Binding qui renvoie ValueIfTrue ou ValueIfFalse selon la valeur
/// de la cible du binding.
/// Equivalent à l'opérateur conditionnel en C# (condition ? valeurSiVrai : valeurSiFaux)
///
public class SwitchExtension : Binding
{
///
/// Initialise une nouvelle instance de SwitchExtension
///
public SwitchExtension()
{
Initialize();
}
///
/// Initialise une nouvelle instance de SwitchExtension, avec le chemin de propriété spécifié
///
/// Chemin de la propriété à binder
public SwitchExtension(string path)
: base(path)
{
Initialize();
}
///
/// Initialise une nouvelle instance de SwitchExtension, avec le chemin de propriété, la valeur si vrai et la valeur si faux spécifiés
///
/// Chemin de la propriété à binder
/// Valeur à renvoyer si la propriété bindée vaut true
/// Valeur à renvoyer si la propriété bindée vaut false
public SwitchExtension(string path, object valueIfTrue, object valueIfFalse)
: base(path)
{
Initialize();
this.ValueIfTrue = valueIfTrue;
this.ValueIfFalse = valueIfFalse;
}
private void Initialize()
{
this.ValueIfTrue = Binding.DoNothing;
this.ValueIfFalse = Binding.DoNothing;
this.Converter = new SwitchConverter(this);
}
///
/// Valeur à renvoyer si la propriété bindée vaut true
///
[ConstructorArgument("valueIfTrue")]
public object ValueIfTrue { get; set; }
///
/// Valeur à renvoyer si la propriété bindée vaut false
///
[ConstructorArgument("valueIfFalse")]
public object ValueIfFalse { get; set; }
private class SwitchConverter : IValueConverter
{
public SwitchConverter(SwitchExtension switchExtension)
{
_switch = switchExtension;
}
private SwitchExtension _switch;
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
try
{
bool b = System.Convert.ToBoolean(value);
return b ? _switch.ValueIfTrue : _switch.ValueIfFalse;
}
catch
{
return DependencyProperty.UnsetValue;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return Binding.DoNothing;
}
#endregion
}
}
}