How to drag and drop external files into WinUI3 apps?

206 views Asked by At

I want to implement the ability to drag and drop files from Windows Explorer inside a WinUI3 app.

I have written a simple code as shown below.

<?xml version="1.0" encoding="utf-8"?>
<Window
    x:Class="App2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App2"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">
    
    <Grid Background="Teal" AllowDrop="True" DragOver="OnDragOver" Drop="OnDrop">
        <Border Background="Red" VerticalAlignment="Center" HorizontalAlignment="Center">
            <TextBlock Text="file drop here!" />
        </Border>
    </Grid>
</Window>
public sealed partial class MainWindow : Window
{
    public MainWindow()
    {
        this.InitializeComponent();
    }


    private void OnDragOver(object sender, DragEventArgs e)
    {
        e.AcceptedOperation = DataPackageOperation.Copy;

        e.DragUIOverride.IsCaptionVisible = false;
        e.DragUIOverride.IsGlyphVisible = false;
    }

    private async void OnDrop(object sender, DragEventArgs e)
    {
        if (e.DataView.Contains(StandardDataFormats.StorageItems))
        {
            var items = await e.DataView.GetStorageItemsAsync();

            foreach (var item in items)
            {
                if (item is StorageFile file)
                {
                }
            }
        }
    }
}

When you drag a file inside the app, you will only see x.

About my project.

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>WinExe</OutputType>
    <TargetFramework>net6.0-windows10.0.19041.0</TargetFramework>
    <TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion>
    ...
    <UseWinUI>true</UseWinUI>
    <EnableMsixTooling>true</EnableMsixTooling>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.WindowsAppSDK" Version="1.4.231008000" />
    <PackageReference Include="Microsoft.Windows.SDK.BuildTools" Version="10.0.22621.756" />
    <Manifest Include="$(ApplicationManifest)" />
  </ItemGroup>
  ...
</Project>

The OnDragOver function should be called when the file is dragged inside the app, and the OnDrop function should be called when the file is released.

0

There are 0 answers