Este artículo se tradujo de forma manual. Mueva el puntero sobre las frases del artículo para ver el texto original. |
Traducción
Original
|
IValueConverter (Interfaz)
Proporciona una forma de aplicar la lógica personalizada a un enlace.
Ensamblado: PresentationFramework (en PresentationFramework.dll)
El tipo IValueConverter expone los siguientes miembros.
Si desea asociar un convertidor de valores a un enlace, cree una clase que implemente la interfaz IValueConverter y, a continuación, los métodos Convert y ConvertBack. Los convertidores pueden cambiar los datos de un tipo a otro, traducir datos basados en información de referencia cultural o modificar otros aspectos de la presentación. Para obtener ejemplos de algunos escenarios típicos del convertidor, vea "Conversión de datos" en Información general sobre el enlace de datos.
Los convertidores de valores tienen en cuenta la referencia cultural. Los métodos Convert y ConvertBack tienen un parámetro culture que indica la información de referencia cultural. Si la información de referencia cultural es no importante para la conversión, puede pasar por alto este parámetro en el convertidor personalizado.
Los métodos Convert y ConvertBack también cuentan con un parámetro denominado parameter para que pueda usar la misma instancia del convertidor con parámetros distintos. Por ejemplo, puede escribir a un convertidor de formato que genere formatos de datos diferentes basados en el parámetro de entrada que use. Puede utilizar la propiedad ConverterParameter de la clase Binding para pasar un parámetro como argumento a los métodos Convert y ConvertBack.
This example shows how to apply conversion to data that is used in bindings.
To convert data during binding, you must create a class that implements the IValueConverter interface, which includes the Convert and ConvertBack methods.
The following example shows the implementation of a date converter that converts the date value passed in so that it only shows the year, the month, and the day. When implementing the IValueConverter interface, it is a good practice to decorate the implementation with a ValueConversionAttribute attribute to indicate to development tools the data types involved in the conversion, as in the following example:
[ValueConversion(typeof(DateTime), typeof(String))] public class DateConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { DateTime date = (DateTime)value; return date.ToShortDateString(); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { string strValue = value as string; DateTime resultDateTime; if (DateTime.TryParse(strValue, out resultDateTime)) { return resultDateTime; } return DependencyProperty.UnsetValue; } }
Once you have created a converter, you can add it as a resource in your Extensible Application Markup Language (XAML) file. In the following example, src maps to the namespace in which DateConverter is defined.
Finally, you can use the converter in your binding using the following syntax. In the following example, the text content of the TextBlock is bound to StartDate, which is a property of an external data source.
<TextBlock Grid.Row="2" Grid.Column="0" Margin="0,0,8,0" Name="startDateTitle" Style="{StaticResource smallTitleStyle}">Start Date:</TextBlock> <TextBlock Name="StartDateDTKey" Grid.Row="2" Grid.Column="1" Text="{Binding Path=StartDate, Converter={StaticResource dateConverter}}" Style="{StaticResource textStyleTextBlock}"/>
The style resources referenced in the above example are defined in a resource section not shown in this topic.
Windows 7, Windows Vista SP1 o posterior, Windows XP SP3, Windows Server 2008 (no se admite Server Core), Windows Server 2008 R2 (se admite Server Core con SP1 o posterior), Windows Server 2003 SP2
.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.