WPF窗口拖放不起作用

时间:2017-09-18 02:17:13

标签: c# wpf xaml drag-and-drop

为什么目标图像image1在我拖动图像img2后没有改变。

我的XAML代码:

<Window x:Class="WpfApplication4.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="463.42" Width="861.214">
<Grid>

    <Image Name="image1" Margin="291,10,297,94" AllowDrop="True" Source="C:/img/0.png" Drop="img1_Drop"/>

    <Button x:Name="btn1" Content="merge" HorizontalAlignment="Left" Margin="753,392,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
    <Button Content="add" HorizontalAlignment="Left" Margin="658,392,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1"/>
</Grid>

这是C#代码:

private void img1_Drop(object sender, DragEventArgs e)
    {

        image1.Source = (System.Windows.Media.ImageSource)e.Data.GetData(typeof(System.Windows.Media.ImageSource));
        //image1.Source = (BitmapImage)e.Data.GetData(DataFormats.Bitmap);

    }

什么都没发生,怎么解决这个问题?

1 个答案:

答案 0 :(得分:0)

您可以直接从丢弃的文件名信息中读取图像,如下所示:

if(e.Data.GetDataPresent(DataFormats.FileDrop))
{
    var filename = ((string[])e.Data.GetData(DataFormats.FileDrop))[0];
    image1.Source = new BitmapImage(new Uri(filename));
}