Interfaccia IValueConverter (System.Windows.Data)

Cambia visualizzazione:
ScriptFree
Riferimento a .NET Framework
Interfaccia IValueConverter
Il presente articolo è stato tradotto manualmente. Per visualizzare questa pagina e contemporaneamente visualizzarne il contenuto in lingua inglese, passare alla visualizzazione semplificata.

Fornisce una modalità per applicare la logica personalizzata a un'associazione.

Spazio dei nomi:  System.Windows.Data
Assembly:  PresentationFramework (in PresentationFramework.dll)
Sintassi

Visual Basic
Public Interface IValueConverter
C#
public interface IValueConverter
Visual C++
public interface class IValueConverter
F#
type IValueConverter =  interface end

Il tipo IValueConverter espone i seguenti membri.

Metodi

  Nome Descrizione
Metodo pubblico Convert Converte un valore.
Metodo pubblico ConvertBack Converte un valore.
In alto
Note

Se si vuole associare un convertitore di valore a un'associazione, creare una classe che implementa l'interfaccia IValueConverter e quindi implementare i metodi Convert e ConvertBack. I convertitori possono modificare dati da uno tipo a un altro, tradurre dati in base a informazioni culturali, o modificare altri aspetti della presentazione. Per esempi di alcuni scenari del convertitore tipici, vedere la "Conversione dati" in Data Binding Overview.

I convertitori di valore hanno il supporto delle impostazioni cultura. Entrambi i metodi Convert e ConvertBack hanno il parametro culture che indica le informazioni culturali. Se le informazioni culturali sono irrilevanti per la conversione, è possibile ignorare tale parametro nel convertitore personalizzato.

I metodi Convert e ConvertBack hanno anche un parametro denominato parameter che consente di utilizzare la stessa istanza del convertitore con parametri diversi. Ad esempio, è possibile scrivere un convertitore di formattazione che produce formati diversi di dati basato sul parametro di input utilizzato. È possibile utilizzare ConverterParameter della classe Binding per passare un parametro come argomento nei metodi Convert e ConvertBack.

Esempi

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:

C#

[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.

XAML

<src:DateConverter x:Key="dateConverter"/>


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.

XAML

<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.

Informazioni sulla versione

.NET Framework

Supportato in: 4, 3.5, 3.0

.NET Framework Client Profile

Supportato in: 4, 3.5 SP1
Piattaforme

Windows 7, Windows Vista SP1 o versione successiva, Windows XP SP3, Windows Server 2008 (componenti di base del server non supportati), Windows Server 2008 R2 (componenti di base del server supportati con SP1 o versione successiva), Windows Server 2003 SP2

.NET Framework non supporta tutte le versioni di ciascuna piattaforma. Per un elenco delle versioni supportate, vedere Requisiti di sistema di .NET Framework.
Vedere anche

Riferimenti

Altre risorse