我需要將圖像文件放入我的WPF應用程序中。當我放入文件時,我目前有一個事件觸發,但我不知道下一步該怎麼做。我如何獲得圖像? sender
是否反映圖像或控件?將文件拖放到WPF中
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?
}
我需要將圖像文件放入我的WPF應用程序中。當我放入文件時,我目前有一個事件觸發,但我不知道下一步該怎麼做。我如何獲得圖像? sender
是否反映圖像或控件?將文件拖放到WPF中
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
class的一個實例。
(該sender
參數包含對引發事件的對象的引用。)
具體地,檢查e.Data
member;如文檔解釋,這將返回對包含拖動事件數據的數據對象(IDataObject
)的引用。
IDataObject
接口提供了許多方法來檢索您之後的數據對象。您可能需要先撥打GetFormats
method開始,以查明您正在使用的數據的格式。 (例如,它是一個實際的圖像還是圖像文件的路徑?)
然後,一旦確定了被拖入文件的格式,就會調用其中一個特定的重載GetData
方法實際檢索特定格式的數據對象。
除了答案A.R.請注意,如果你想使用TextBox
放棄,你必須知道以下的東西。
TextBox
似乎已經對DragAndDrop
進行了一些默認處理。如果你的數據對象是String
,它就可以工作。其他類型不處理,你會得到禁止鼠標效果和你的Drop處理程序永遠不會被調用。
看起來像你可以使用e.Handled
到真正的在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);
}
}
AR的例子沒有預覽DragOver處理程序,這是非常重要的這一切都會在一起。榮譽。 – 2017-02-04 02:13:27
真棒工作的魅力,只是交換 「HandleFileOpen(文件[0]);」到「foreach(文件中的字符串文件){Openfile(文件);}」 - 謝謝:) – 2011-04-14 13:36:27
這不是爲我工作:/ – 2014-12-30 16:25:10
@Matteo關心詳細說明? – 2014-12-30 16:27:31