Condividi tramite


Procedura: Aprire un file trascinato su un controllo RichTextBox

In Windows Presentation Foundation (WPF), i controlli TextBox, RichTextBoxe FlowDocument dispongono di funzionalità predefinite di trascinamento della selezione. La funzionalità predefinita abilita il trascinamento della selezione del testo all'interno e tra i controlli. Tuttavia, non abilita l'apertura di un file trascinando il file sul controllo. Questi controlli contrassegnano anche gli eventi di trascina e rilascia come gestiti. Di conseguenza, per impostazione predefinita, non è possibile aggiungere gestori eventi personalizzati per fornire funzionalità per aprire i file eliminati.

Per aggiungere una gestione aggiuntiva per gli eventi di trascinamento in questi controlli, usare il metodo AddHandler(RoutedEvent, Delegate, Boolean) per aggiungere i relativi gestori eventi. Impostare il parametro handledEventsToo su true affinché il gestore specificato venga richiamato per un evento indirizzato già contrassegnato come gestito da un altro elemento lungo la route dell'evento.

Suggerimento

È possibile sostituire la funzionalità predefinita di trascinamento della selezione di TextBox, RichTextBoxe FlowDocument gestendo le versioni di anteprima degli eventi di trascinamento della selezione e contrassegnando gli eventi di anteprima come gestiti. Tuttavia, ciò disabiliterà la funzionalità predefinita di trascinamento della selezione e non è consigliata.

Esempio

Nell'esempio seguente viene illustrato come aggiungere gestori per gli eventi DragOver e Drop in un RichTextBox. Questo esempio usa il metodo AddHandler(RoutedEvent, Delegate, Boolean) e imposta il parametro handledEventsToo su true in modo che i gestori eventi vengano richiamati anche se il RichTextBox contrassegna questi eventi come gestiti. Il codice nei gestori eventi aggiunge funzionalità per aprire un file di testo trascinato sulla RichTextBox.

Per testare questo esempio, trascinare un file di testo o un file RTF da Esplora Risorse al RichTextBox. Il file verrà aperto nel RichTextBox. Se si preme MAIUSC prima dell'eliminazione del file, il file verrà aperto come testo normale.

<RichTextBox x:Name="richTextBox1"
             AllowDrop="True" />
public MainWindow()
{
    InitializeComponent();

    // Add using System.Windows.Controls;
    richTextBox1.AddHandler(RichTextBox.DragOverEvent, new DragEventHandler(RichTextBox_DragOver), true);
    richTextBox1.AddHandler(RichTextBox.DropEvent, new DragEventHandler(RichTextBox_Drop), true);
}

private void RichTextBox_DragOver(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        e.Effects = DragDropEffects.All;
    }
    else
    {
        e.Effects = DragDropEffects.None;
    }
    e.Handled = false;
}

private void RichTextBox_Drop(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        string[] docPath = (string[])e.Data.GetData(DataFormats.FileDrop);

        // By default, open as Rich Text (RTF).
        var dataFormat = DataFormats.Rtf;

        // If the Shift key is pressed, open as plain text.
        if (e.KeyStates == DragDropKeyStates.ShiftKey)
        {
            dataFormat = DataFormats.Text;
        }

        System.Windows.Documents.TextRange range;
        System.IO.FileStream fStream;
        if (System.IO.File.Exists(docPath[0]))
        {
            try
            {
                // Open the document in the RichTextBox.
                range = new System.Windows.Documents.TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd);
                fStream = new System.IO.FileStream(docPath[0], System.IO.FileMode.OpenOrCreate);
                range.Load(fStream, dataFormat);
                fStream.Close();
            }
            catch (System.Exception)
            {
                MessageBox.Show("File could not be opened. Make sure the file is a text file.");
            }
        }
    }
}
Public Sub New()
    InitializeComponent()

    richTextBox1.AddHandler(RichTextBox.DragOverEvent, New DragEventHandler(AddressOf RichTextBox_DragOver), True)
    richTextBox1.AddHandler(RichTextBox.DropEvent, New DragEventHandler(AddressOf RichTextBox_Drop), True)

End Sub

Private Sub RichTextBox_DragOver(sender As Object, e As DragEventArgs)
    If e.Data.GetDataPresent(DataFormats.FileDrop) Then
        e.Effects = DragDropEffects.All
    Else
        e.Effects = DragDropEffects.None
    End If
    e.Handled = False
End Sub

Private Sub RichTextBox_Drop(sender As Object, e As DragEventArgs)
    If e.Data.GetDataPresent(DataFormats.FileDrop) Then
        Dim docPath As String() = TryCast(e.Data.GetData(DataFormats.FileDrop), String())

        ' By default, open as Rich Text (RTF).
        Dim dataFormat = DataFormats.Rtf

        ' If the Shift key is pressed, open as plain text.
        If e.KeyStates = DragDropKeyStates.ShiftKey Then
            dataFormat = DataFormats.Text
        End If

        Dim range As TextRange
        Dim fStream As IO.FileStream
        If IO.File.Exists(docPath(0)) Then
            Try
                ' Open the document in the RichTextBox.
                range = New TextRange(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd)
                fStream = New IO.FileStream(docPath(0), IO.FileMode.OpenOrCreate)
                range.Load(fStream, dataFormat)
                fStream.Close()
            Catch generatedExceptionName As System.Exception
                MessageBox.Show("File could not be opened. Make sure the file is a text file.")
            End Try
        End If
    End If
End Sub