// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MethodToValueConverter.cs" company="Catel development team">
// Copyright (c) 2008 - 2011 Catel development team. All rights reserved.
// </copyright>
// <summary>
// Converter to convert the result of a method to a value. This makes it possible to bind to a method.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Globalization;
using System.Reflection;
using System.Windows.Data;
using Catel.Windows.Properties;
namespace Catel.Windows.Data.Converters
{
/// <summary>
/// Converter to convert the result of a method to a value. This makes it possible to bind to a method.
/// </summary>
/// <example>
/// {Binding MyObject, Converter={StaticResource MethodToValueConverter}, ConverterParameter='MyMethod'}
/// </example>
/// <remarks>
/// Code originally comes from http://stackoverflow.com/questions/502250/bind-to-a-method-in-wpf.
/// </remarks>
#if !SILVERLIGHT
[ValueConversion(typeof(string), typeof(object))]
#endif
public class MethodToValueConverter : IValueConverter
{
/// <summary>
/// Converts a value.
/// </summary>
/// <param name="value">The value produced by the binding source.</param>
/// <param name="targetType">The type of the binding target property.</param>
/// <param name="parameter">The converter parameter to use.</param>
/// <param name="culture">The culture to use in the converter.</param>
/// <returns>
/// A converted value. If the method returns null, the valid null value is used.
/// </returns>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var methodName = parameter as string;
if (value == null || methodName == null)
{
return value;
}
var methodInfo = value.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, new Type[0], null);
if (methodInfo == null)
{
return value;
}
return methodInfo.Invoke(value, new object[0]);
}
/// <summary>
/// Converts a value.
/// </summary>
/// <param name="value">The value that is produced by the binding target.</param>
/// <param name="targetType">The type to convert to.</param>
/// <param name="parameter">The converter parameter to use.</param>
/// <param name="culture">The culture to use in the converter.</param>
/// <returns>
/// A converted value. If the method returns null, the valid null value is used.
/// </returns>
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException(Exceptions.MethodToValueConverterOnlySupportsOneWayBinding);
}
}
}