从桌面拖动图像并将其拖放到位图查看器

时间:2012-11-14 11:32:20

标签: wpf drag-and-drop bitmapimage

我想从桌面拖动图片(人物图片),然后将其放到我的wpf应用程序

任何资源?

1 个答案:

答案 0 :(得分:3)

XAML:

<Window x:Class="_13378018.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" AllowDrop="True" Drop="OnDrop">
    <Grid>
        <Image x:Name="imageViewer"/>
    </Grid>
</Window>

代码隐藏:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
    }

    private BitmapImage LoadImageFromFile(string filename)
    {
        using (var fs = File.OpenRead(filename))
        {
            var img = new BitmapImage();
            img.BeginInit();
            img.CacheOption = BitmapCacheOption.OnLoad;
            // Downscaling to keep the memory footprint low
            img.DecodePixelWidth = (int)SystemParameters.PrimaryScreenWidth;
            img.StreamSource = fs;
            img.EndInit();
            return img;
        }
    }

    private void OnDrop(object sender, DragEventArgs e)
    {
        var data = e.Data as DataObject;
        if (data.ContainsFileDropList())
        {
            var files = data.GetFileDropList();
            imageViewer.Source = LoadImageFromFile(files[0]);
        }
    }
}