在 Windows Presentation Foundation (WPF) 中,TextBox、RichTextBox 和 FlowDocument 控件都具有内置拖放功能。 通过该内置功能,可在控件内和控件之间拖放文本。 但是,该功能不支持通过将文件放到控件上来打开文件。 这些控件还会将拖放事件标记为已处理。 因此,在默认情况下,您无法添加自己的事件处理程序以提供用于打开所放置文件的功能。
若要为这些控件中的拖放事件添加其他处理,请使用 AddHandler(RoutedEvent, Delegate, Boolean) 方法为拖放事件添加事件处理程序。 将 handledEventsToo 参数设置为 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.");
}
}
}
}
转自:MSDN http://msdn.microsoft.com/zh-cn/library/vstudio/hh144798