[英]Drag and drop files into WPF
我需要將圖像文件放入我的WPF應用程序中。 當我放下文件時,我目前有一個事件觸發,但我不知道接下來該怎么做。 我如何獲得圖像? sender
對象是圖像還是控件?
private void ImagePanel_Drop(object sender, DragEventArgs e)
{
//what next, dont know how to get the image object, can I get the file path here?
}
這基本上就是你想要做的。
private void ImagePanel_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
// Note that you can have more than one file.
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
// Assuming you have one file that you care about, pass it off to whatever
// handling code you have defined.
HandleFileOpen(files[0]);
}
}
另外,不要忘記在XAML中實際連接事件,以及設置AllowDrop
屬性。
<StackPanel Name="ImagePanel" Drop="ImagePanel_Drop" AllowDrop="true">
...
</StackPanel>
圖像文件包含在e
參數中,該參數是DragEventArgs
類的一個實例。
( sender
參數包含對引發事件的對象的引用。)
具體來說,檢查e.Data
成員 ; 如文檔所述,這將返回對包含來自拖動事件的數據的數據對象( IDataObject
)的引用。
IDataObject
接口提供了許多方法來檢索您所追求的數據對象。 您可能希望首先調用GetFormats
方法 ,以找出您正在使用的數據的格式。 (例如,它是實際圖像還是圖像文件的路徑?)
然后,一旦確定了被拖入文件的格式,就會調用GetData
方法的一個特定重載來實際檢索特定格式的數據對象。
另外要回答AR請注意,如果你想使用TextBox
,你必須知道以下內容。
TextBox
似乎已經為DragAndDrop
進行了一些默認處理。 如果您的數據對象是String
,它就可以正常工作。 其他類型未處理,您將獲得Forbidden鼠標效果,並且永遠不會調用Drop處理程序。
好像你可以讓自己的處理與e.Handled
為true在PreviewDragOver
事件處理程序。
XAML
<TextBox AllowDrop="True" x:Name="RtbInputFile" HorizontalAlignment="Stretch" HorizontalScrollBarVisibility="Visible" VerticalScrollBarVisibility="Visible" />
C#
RtbInputFile.Drop += RtbInputFile_Drop;
RtbInputFile.PreviewDragOver += RtbInputFile_PreviewDragOver;
private void RtbInputFile_PreviewDragOver(object sender, DragEventArgs e)
{
e.Handled = true;
}
private void RtbInputFile_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
// Note that you can have more than one file.
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
var file = files[0];
HandleFile(file);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.