Dati e oggetti dati

I dati trasferiti come parte di un'operazione di trascinamento della selezione vengono archiviati in un oggetto dati. Concettualmente, un oggetto dati è costituito da una o più delle coppie seguenti:

  • Oggetto Object contenente i dati effettivi.

  • Identificatore di formato dati corrispondente.

I dati stessi possono essere costituiti da qualsiasi elemento che può essere rappresentato come base Object. Il formato dati corrispondente è una stringa o Type che fornisce un suggerimento sul formato in cui si trovano i dati. Gli oggetti dati supportano l'hosting di più coppie di formato dati/dati; ciò consente a un singolo oggetto dati di fornire dati in più formati.

Oggetti dati

Tutti gli oggetti dati devono implementare l'interfaccia IDataObject , che fornisce il set standard seguente di metodi che consentono e facilitano il trasferimento dei dati.

Method Riepilogo
GetData Recupera un oggetto dati in un formato di dati specificato.
GetDataPresent Verifica se i dati sono disponibili in o possono essere convertiti in un formato specificato.
GetFormats Restituisce un elenco di formati in cui sono archiviati i dati in questo oggetto dati o in cui possono essere convertiti.
SetData Archivia i dati specificati in questo oggetto dati.

WPF fornisce un'implementazione di base di IDataObject nella DataObject classe . La classe stock DataObject è sufficiente per molti scenari comuni di trasferimento dei dati.

Esistono diversi formati predefiniti, ad esempio bitmap, CSV, file, HTML, RTF, stringa, testo e audio. Per informazioni sui formati di dati predefiniti forniti con WPF, vedere l'argomento di riferimento sulla DataFormats classe.

Gli oggetti dati in genere includono una funzionalità per la conversione automatica dei dati archiviati in un formato diverso durante l'estrazione dei dati; questa funzionalità viene definita conversione automatica. Quando si eseguono query sui formati di dati disponibili in un oggetto dati, è possibile filtrare i formati di dati convertibili automaticamente dai formati di dati nativi chiamando il GetFormats(Boolean) metodo o GetDataPresent(String, Boolean) e specificando il autoConvert parametro come false. Quando si aggiungono dati a un oggetto dati con il SetData(String, Object, Boolean) metodo , è possibile impedire la conversione automatica dei dati impostando il autoConvert parametro su false.

Utilizzo di oggetti dati

In questa sezione vengono descritte le tecniche comuni per la creazione e l'uso di oggetti dati.

Creazione di nuovi oggetti dati

La DataObject classe fornisce diversi costruttori di overload che facilitano il popolamento di una nuova DataObject istanza con una singola coppia di formato dati/dati.

Il codice di esempio seguente crea un nuovo oggetto dati e usa uno dei costruttori DataObjectdi overload (DataObject(String, Object)) per inizializzare l'oggetto dati con una stringa e un formato di dati specificato. In questo caso, il formato dei dati viene specificato da una stringa; la DataFormats classe fornisce un set di stringhe di tipi predefinite. La conversione automatica dei dati archiviati è consentita per impostazione predefinita.

string stringData = "Some string data to store...";
string dataFormat = DataFormats.UnicodeText;
DataObject dataObject = new DataObject(dataFormat, stringData);
Dim stringData As String = "Some string data to store..."
Dim dataFormat As String = DataFormats.UnicodeText
Dim dataObject As New DataObject(dataFormat, stringData)

Per altri esempi di codice che crea un oggetto dati, vedere Creare un oggetto dati.

Archiviazione dei dati in più formati

Un singolo oggetto dati è in grado di archiviare i dati in più formati. L'uso strategico di più formati di dati all'interno di un singolo oggetto dati rende potenzialmente l'oggetto dati utilizzabile da un'ampia gamma di destinazioni di rilascio rispetto a se fosse possibile rappresentare solo un singolo formato di dati. Si noti che, in generale, un'origine di trascinamento deve essere indipendente dai formati di dati utilizzabili da potenziali destinazioni di rilascio.

Nell'esempio seguente viene illustrato come utilizzare il SetData(String, Object) metodo per aggiungere dati a un oggetto dati in più formati.

DataObject dataObject = new DataObject();
string sourceData = "Some string data to store...";

// Encode the source string into Unicode byte arrays.
byte[] unicodeText = Encoding.Unicode.GetBytes(sourceData); // UTF-16
byte[] utf8Text = Encoding.UTF8.GetBytes(sourceData);
byte[] utf32Text = Encoding.UTF32.GetBytes(sourceData);

// The DataFormats class does not provide data format fields for denoting
// UTF-32 and UTF-8, which are seldom used in practice; the following strings
// will be used to identify these "custom" data formats.
string utf32DataFormat = "UTF-32";
string utf8DataFormat  = "UTF-8";

// Store the text in the data object, letting the data object choose
// the data format (which will be DataFormats.Text in this case).
dataObject.SetData(sourceData);
// Store the Unicode text in the data object.  Text data can be automatically
// converted to Unicode (UTF-16 / UCS-2) format on extraction from the data object;
// Therefore, explicitly converting the source text to Unicode is generally unnecessary, and
// is done here as an exercise only.
dataObject.SetData(DataFormats.UnicodeText, unicodeText);
// Store the UTF-8 text in the data object...
dataObject.SetData(utf8DataFormat, utf8Text);
// Store the UTF-32 text in the data object...
dataObject.SetData(utf32DataFormat, utf32Text);
Dim dataObject As New DataObject()
Dim sourceData As String = "Some string data to store..."

' Encode the source string into Unicode byte arrays.
Dim unicodeText() As Byte = Encoding.Unicode.GetBytes(sourceData) ' UTF-16
Dim utf8Text() As Byte = Encoding.UTF8.GetBytes(sourceData)
Dim utf32Text() As Byte = Encoding.UTF32.GetBytes(sourceData)

' The DataFormats class does not provide data format fields for denoting
' UTF-32 and UTF-8, which are seldom used in practice; the following strings 
' will be used to identify these "custom" data formats.
Dim utf32DataFormat As String = "UTF-32"
Dim utf8DataFormat As String = "UTF-8"

' Store the text in the data object, letting the data object choose
' the data format (which will be DataFormats.Text in this case).
dataObject.SetData(sourceData)
' Store the Unicode text in the data object.  Text data can be automatically
' converted to Unicode (UTF-16 / UCS-2) format on extraction from the data object; 
' Therefore, explicitly converting the source text to Unicode is generally unnecessary, and
' is done here as an exercise only.
dataObject.SetData(DataFormats.UnicodeText, unicodeText)
' Store the UTF-8 text in the data object...
dataObject.SetData(utf8DataFormat, utf8Text)
' Store the UTF-32 text in the data object...
dataObject.SetData(utf32DataFormat, utf32Text)

Esecuzione di query su un oggetto dati per i formati disponibili

Poiché un singolo oggetto dati può contenere un numero arbitrario di formati di dati, gli oggetti dati includono funzionalità per il recupero di un elenco di formati di dati disponibili.

Il codice di esempio seguente usa l'overload GetFormats per ottenere una matrice di stringhe che denota tutti i formati di dati disponibili in un oggetto dati (sia nativo che per conversione automatica).

DataObject dataObject = new DataObject("Some string data to store...");

// Get an array of strings, each string denoting a data format
// that is available in the data object.  This overload of GetDataFormats
// returns all available data formats, native and auto-convertible.
string[] dataFormats = dataObject.GetFormats();

// Get the number of data formats present in the data object, including both
// auto-convertible and native data formats.
int numberOfDataFormats = dataFormats.Length;

// To enumerate the resulting array of data formats, and take some action when
// a particular data format is found, use a code structure similar to the following.
foreach (string dataFormat in dataFormats)
{
    if (dataFormat == DataFormats.Text)
    {
        // Take some action if/when data in the Text data format is found.
        break;
    }
    else if(dataFormat == DataFormats.StringFormat)
    {
        // Take some action if/when data in the string data format is found.
        break;
    }
}
Dim dataObject As New DataObject("Some string data to store...")

' Get an array of strings, each string denoting a data format
' that is available in the data object.  This overload of GetDataFormats
' returns all available data formats, native and auto-convertible.
Dim dataFormats() As String = dataObject.GetFormats()

' Get the number of data formats present in the data object, including both
' auto-convertible and native data formats.
Dim numberOfDataFormats As Integer = dataFormats.Length

' To enumerate the resulting array of data formats, and take some action when
' a particular data format is found, use a code structure similar to the following.
For Each dataFormat As String In dataFormats
    If dataFormat = System.Windows.DataFormats.Text Then
        ' Take some action if/when data in the Text data format is found.
        Exit For
    ElseIf dataFormat = System.Windows.DataFormats.StringFormat Then
        ' Take some action if/when data in the string data format is found.
        Exit For
    End If
Next dataFormat

Per altri esempi di codice che esegue una query su un oggetto dati per i formati di dati disponibili, vedere Elencare i formati di dati in un oggetto dati. Per esempi di query su un oggetto dati per la presenza di un formato di dati specifico, vedere Determinare se un formato dati è presente in un oggetto dati.

Recupero di dati da un oggetto dati

Il recupero di dati da un oggetto dati in un formato specifico implica semplicemente la GetData chiamata di uno dei metodi e la specifica del formato dati desiderato. Uno dei GetDataPresent metodi può essere usato per verificare la presenza di un formato dati specifico. GetData restituisce i dati in un Objectoggetto , a seconda del formato di dati, è possibile eseguire il cast di questo oggetto in un contenitore specifico del tipo.

Il codice di esempio seguente usa l'overload GetDataPresent(String) per verificare se è disponibile un formato di dati specificato (nativo o tramite conversione automatica). Se il formato specificato è disponibile, l'esempio recupera i dati usando il GetData(String) metodo .

DataObject dataObject = new DataObject("Some string data to store...");

string desiredFormat = DataFormats.UnicodeText;
byte[] data = null;

// Use the GetDataPresent method to check for the presence of a desired data format.
// This particular overload of GetDataPresent looks for both native and auto-convertible
// data formats.
if (dataObject.GetDataPresent(desiredFormat))
{
    // If the desired data format is present, use one of the GetData methods to retrieve the
    // data from the data object.
    data = dataObject.GetData(desiredFormat) as byte[];
}
Dim dataObject As New DataObject("Some string data to store...")

Dim desiredFormat As String = DataFormats.UnicodeText
Dim data() As Byte = Nothing

' Use the GetDataPresent method to check for the presence of a desired data format.
' This particular overload of GetDataPresent looks for both native and auto-convertible 
' data formats.
If dataObject.GetDataPresent(desiredFormat) Then
    ' If the desired data format is present, use one of the GetData methods to retrieve the
    ' data from the data object.
    data = TryCast(dataObject.GetData(desiredFormat), Byte())
End If

Per altri esempi di codice che recupera dati da un oggetto dati, vedere Recuperare dati in un formato dati specifico.

Rimozione di dati da un oggetto dati

I dati non possono essere rimossi direttamente da un oggetto dati. Per rimuovere in modo efficace i dati da un oggetto dati, seguire questa procedura:

  1. Creare un nuovo oggetto dati che conterrà solo i dati che si desidera conservare.

  2. "Copiare" i dati desiderati dall'oggetto dati precedente al nuovo oggetto dati. Per copiare i dati, utilizzare uno dei GetData metodi per recuperare un Object oggetto contenente i dati non elaborati e quindi utilizzare uno dei SetData metodi per aggiungere i dati al nuovo oggetto dati.

  3. Sostituire l'oggetto dati precedente con quello nuovo.

Nota

I SetData metodi aggiungono solo dati a un oggetto dati e non sostituiscono i dati, anche se il formato dati e dati sono esattamente uguali a una chiamata precedente. La chiamata SetData due volte per gli stessi dati e lo stesso formato di dati comporterà la presenza del formato dati/dati due volte nell'oggetto dati.