// -------------------------------------------------------------------------------------------------------------------- // <copyright file="NullableValueConverter.cs" company="Catel development team"> // Copyright (c) 2008 - 2011 Catel development team. All rights reserved. // </copyright> // <summary> // Converts a value to a representive value for nullable. // </summary> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Windows.Data; namespace Catel.Windows.Data.Converters { /// <summary> /// Converts a value to a representive value for nullable. /// </summary> /// <remarks>Resolves problem with databinding with nullables. When textbox hasn't a value then null is expected as return value.</remarks> #if !SILVERLIGHT [ValueConversion(typeof(object), typeof(object))] #endif public class NullableValueConverter : IValueConverter { /// <summary> /// Convert to targettype. /// </summary> /// <param name="value">A value.</param> /// <param name="targetType">Target type (only types with standard conversion are supported, System.Convert.ChangeType is used for conversion).</param> /// <param name="parameter">Parameter.</param> /// <param name="culture">A culture.</param> /// <returns>Converted value.</returns> public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { // not the interresting part for us, use default conversion return System.Convert.ChangeType(value, targetType, culture); } /// <summary> /// Convert back to nullable object. /// </summary> /// <param name="value">A value.</param> /// <param name="targetType">Target type (only types with standard conversion are supported, System.Convert.ChangeType is used for conversion).</param> /// <param name="parameter">Parameter.</param> /// <param name="culture">A culture.</param> /// <returns>Converted value.</returns> public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { object result = null; string str = value as string; if (value != null && (str == null || !string.IsNullOrEmpty(str.Trim()))) { Type underlyingType = Nullable.GetUnderlyingType(targetType) ?? targetType; try { result = System.Convert.ChangeType(value, underlyingType, culture); } catch { // ignore exceptions } } return result; } } }
By viewing downloads associated with this article you agree to the Terms of use and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
Math Primers for Programmers